【问题标题】:How to Strictly specify a return type Angular4/ionic3如何严格指定返回类型 Angular4/ionic3
【发布时间】:2018-08-09 07:09:14
【问题描述】:

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

这些是我面临的问题: 1. nodejs服务器总是返回一个json数据数组,这使得我必须访问ionic3中的数据作为索引(数据[0])而不是点符号(数据。)。请问我该如何解决? 2. 从数据库返回的数据将大量数据转储回客户端,我想使用我正在导入服务的 typescript 接口过滤这些数据。我将在适当的位置展示我的代码摘录

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;

即使有了这些,我仍然会得到一个数据转储,我可以通过索引访问它,它还会从数据库中转储我不需要的所有不必要的数据

任何帮助将不胜感激

【问题讨论】:

  • 为什么不像我刚刚在stackoverflow.com/questions/49044223/… 中发布的那样在您的服务中使用地图?
  • 像这样: import 'rxjs/add/operator/map' getMyProfile(data){ this.http.get(this.apiUrl + data) .map(result => { 返回结果; }) .pipe(catchError(this.handleError)) }
  • 一个接口不能完成过滤,一个接口根本不会对你的数据做任何活跃的事情,它只是限制了 TypeScript 编译器认为你的代码语法可以接受的内容。当 TypeScript 变成 JavaScript 时,接口就完全消失了。在服务器代码中使用 Eliseo 建议的地图可以完成您正在寻找的内容。
  • @user3118363 不,不是这样。你的 map() 没有做任何事情。它按原样返回您从后端获得的值,而不进行任何转换。它必须做的是将您从 backedn 获得的数据转换为您想要的格式。 TypeScript 不会为您做到这一点。它只是一个编译器。
  • 那么,请问我该怎么做?

标签: node.js angular mongodb typescript ionic3


【解决方案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))     
  }

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

【讨论】:

  • 是的,是的,是的!谢谢十亿。竖起大拇指
  • @user3118363 - 在 StackOverflow 上,除了将其标记为已接受之外,竖起大拇指的最佳方式是对答案进行投票。
  • 我将其标记为已接受,但我找不到点赞按钮或类似的东西,你能帮我找到吗?
  • 我想我明白了。左边的向上箭头。明白了,做到了
猜你喜欢
  • 2019-12-14
  • 1970-01-01
  • 1970-01-01
  • 2018-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-03
  • 1970-01-01
相关资源
最近更新 更多