问题:
我正在尝试使用以下方法查询我的前端角度2服务中当前登录的用户:
UserModel.findById(userID, function (err, user) {
看来这种行为可以从浏览器中获取,如何从我的服务中查询用户?
错误:
使用webpack运行npm run build
,然后npm start
:
user.js?b9cb:19 Uncaught TypeError: mongoose.model is not a function
这让我在网上搜索错误的含义,并有效地发现mongoose不支持来自客户端的查询?
https://github.com/Automattic/mongoose/issues/4779
CODE:
模型/用户
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var mongooseUniqueValidator = require('mongoose-unique-validator');
var schema = new Schema({
firstName: {type: String, required: true},
lastName: {type: String, required: true},
password: {type: String, required: true},
email: {type: String, required: true, unique: true},
polls: [{type: Schema.Types.ObjectId, ref: 'Poll'}],
votes: [{
poll: {type: Schema.Types.ObjectId, ref: 'Poll'},
choice: {type: Number},
}],
});
schema.plugin(mongooseUniqueValidator);
module.exports = mongoose.model('User', schema);
client.service
var UserModel = require('../../../models/user');
voted(poll: Poll, userID: string, choice: number) {
UserModel.findById(userID, function (err, user) {
var result = "";
for (var i = 0; i < user.votes.length; i ++) {
if (user.votes[i].poll == poll.pollId) {
result = "disabled";
if (user.votes[i].choice == choice) {
result = "selected";
}
}
}
return result;
})
}
答案 0 :(得分:1)
检查Angular2的http模块以发出请求。这是一个GET请求,但我确定如果您愿意,可以提出所有其他请求。
import { Component } from '@angular/core';
import { Http } from '@angular/http';
@Component({
selector: 'http-app',
templateUrl: 'your-template.html'
})
class YourComponent {
constructor(http: Http) {
http.get('your-endpoint')
.map(response => response.json())
.subscribe(json => this.json = json);
}
}