简体   繁体   English

如何严格指定返回类型 Angular4/ionic3

[英]How to Strictly specify a return type Angular4/ionic3

Please I'm trying to specify a particular return type to only include the data that i need from a mongodb server using nodejs.请我尝试指定一个特定的返回类型,以仅包含我使用 nodejs 从 mongodb 服务器中需要的数据。

These are the issues that i'm facing: 1. the nodejs server always returns an array of json data, which makes it compulsory for me to access the data in ionic3 as indexes(data[0]) instead of dot notation(data.).这些是我面临的问题: 1. nodejs 服务器总是返回一个 json 数据数组,这使得我必须将 ionic3 中的数据作为索引(data[0])而不是点符号(data. )。 How can i fix this please ?我该如何解决这个问题? 2. the data that's being returned from the database dumps a lot of data back to the client side, I want to filter this data using a typescript interface which i'm importing into the service. 2.从数据库返回的数据将大量数据转储回客户端,我想使用我导入到服务中的打字稿接口过滤这些数据。 I'm going to show an extract of my code in place我将在适当的位置展示我的代码的摘录

ProfileModel interface 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
        }
}

The Profile Service Provider function 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.")
  }

Profile Route Server Side Code配置文件路由服务器端代码

//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;

Even with these in place, I still get a data dump, that i access with an index and also, it dumps all the unnecessary datas that i don't need from the db即使有了这些,我仍然会得到一个数据转储,我用索引访问它,而且它从数据库中转储了我不需要的所有不必要的数据

Please any help would be greatly appreciated请任何帮助将不胜感激

You must use httpClient, NOT http -then you needn't JSON.stringify你必须使用 httpClient,而不是 http -那么你就不需要 JSON.stringify

if you get an unique value, you can simple如果你得到一个独特的价值,你可以简单

//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))     
  }

If you get an array -several data-, you can如果你得到一个数组——几个数据——,你可以

// 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))     
  }

MoreOver you can transform the array MoreOver 你可以转换数组

// 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))     
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM