【发布时间】: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