如何严格指定返回类型Angular 4 / ionic 3

问题描述 投票:1回答:1

请我尝试指定一个特定的返回类型,以便仅使用nodejs包含mongodb服务器所需的数据。

这些是我面临的问题:1。nodejs服务器总是返回一个json数据数组,这使得我必须访问ionic3中的数据作为索引(data [0])而不是点符号(数据)。 )。我该怎么办呢? 2.从数据库返回的数据将大量数据转发回客户端,我想使用我导入服务的打字稿界面过滤这些数据。我将展示我的代码的摘录

ProfileModel接口

**(profileModel.ts)**

export interface ProfileModel{
  name : {
            firstName : string,
            lastName : string
    },
    login : {
            username: string
    },

        sex : string,
        address: string,
        status: string,
        coverageArea: string,
        email : string,
        position: string,
        location : {
            latitude: number,
            longitude: number
        }
}

Profile Service Provider功能

**(profile.ts)**

import { ProfileModel } from './profileModel';
  getMyProfile(data){
    return this.http.get<ProfileModel>(this.apiUrl + data)
    .pipe(catchError(this.handleError))     
  }



  private handleError(error: HttpErrorResponse){
      if(error.error instanceof ErrorEvent){
          // A client-side or network error occured
          console.error("An error occured: ", error.error.message)
      } else {
          // The backend returned unsuccessful response
          // The response body may contain clues as to what happened
          console.error(`Backend returned code ${error.status}, `+
            `body was: ${error.error}`);
      }
      return new ErrorObservable("Network Error, please try again later.")
  }

配置路由服务器端代码

//Set up
let express = require("express");
let router = express.Router();

let staffModel = require("../schema");


router.get("/profile/:user", function(req, res){ 
    //let check = req.params();
    staffModel.find({"login.username": req.param("user")})
        .then(data=> {
            res.setHeader("Content-Type", "application/json");
            let check = JSON.stringify(data);
            res.send(check);
        })
        .catch(err=> res.send({"error": "There's an issue with the server."}))
});

module.exports = router;

即使有这些,我仍然得到一个数据转储,我使用索引访问,并且,它从垃圾邮件转储我不需要的所有不必要的数据

如有任何帮助,将不胜感激

node.js angular mongodb typescript ionic3
1个回答
1
投票

您必须使用httpClient,而不是http - 然后您不需要JSON.stringify

如果你得到一个独特的价值,你可以简单

//I supouse that you received "data:[{...}]"
getMyProfile(data){
    return this.http.get<ProfileModel>(this.apiUrl + data)
    .map(result=>{  //don't return result, just result.data[0]
       return result.data[0];
    })
    .pipe(catchError(this.handleError))     
  }

如果你得到一个数组 - 几个数据 - 你可以

// data:[{...},{...}]
getMyProfile(data){
    return this.http.get<ProfileModel>(this.apiUrl + data)
    .map(result=>{  //don't return result, just result.data
       return result.data 
    })
    .pipe(catchError(this.handleError))     
  }

更多你可以改造阵列

// data:[{id:0,val:'aaa',val2:'bbb'},{id:1,val:'ccc',val2:'ddd'}]
getMyProfile(data){
    return this.http.get<ProfileModel>(this.apiUrl + data)
    .map(result=>{                 //don't return result, just result.data
                                   //but, transform the data
       return result.data.map(d=>{ //e.g. I don't want "val2"
           id:d.id,
           val:d.val
       }) 
    })
    .pipe(catchError(this.handleError))     
  }
© www.soinside.com 2019 - 2024. All rights reserved.