[英]How to pass a parameter from angular 2 service to node js function? MEAN
I have a posts collection and each post has an id and userId . 我有一个帖子集合,每个帖子都有一个id和userId 。
I want to find all posts for a specific user (using userId property).. 我想查找特定用户的所有帖子 (使用userId属性)。
here is my angular2 service: 这是我的angular2服务:
export class PostsService {
private _url = '/api/posts';
constructor(private _http: Http) { }
getPosts(): Observable<Post[]> {
return this._http.get(this._url).map(res => res.json());
}
getUserPosts(userId: number) {
return this._http.get(this._url + '/' + userId).map(posts => posts.json());
}
}
and my nodejs code : 和我的nodejs代码:
router.get('/posts', function(req, res) {
post.find({}).exec(function(err, posts) {
if (err) {
console.log("ERROR FETCHING POSTS!!");
} else {
res.json(posts);
}
});
});
router.get('/posts/:id', function(req, res) {
post.findById(req.params.id).exec(function(err, posts) {
if (err) {
console.log("ERROR FETCHING POSTS!!" + err);
} else {
res.json(posts);
}
});
});
You need to send query params
to the backend to be able to filter them in you nodejs controllers.In your Angular Service you'll have something like this: 您需要将query params
发送到后端,以便能够在Node.js控制器中对其进行过滤。在Angular Service中,您将具有以下内容:
export class PostsService {
private _url = '/api/posts';
constructor(private _http: Http) { }
getPosts(): Observable<Post[]> {
return this._http.get(this._url).map(res => res.json());
}
getUsersPost():Observable<Post[]>{
let params - new HttpParams();
params = params.append('user_id', userIdValue );
return this._http.get(this._url, { params: params }). subscribe(....more code)
}
getUserPosts(userId: number) {
return this._http.get(this._url + '/' + userId).map(posts => posts.json());
}
}
the final URL would be something like this: /api/posts?user_id=userIdValue
.You need to import HttpParams
from '@angular/common/http'
I'm supposing you have Angular > 4.3, for more info about HttpParams
refer to Angular Official Doc 最终的URL应该是这样的: /api/posts?user_id=userIdValue
。您需要从'@angular/common/http'
导入HttpParams
我假设您使用Angular> 4.3,有关HttpParams
更多信息请参考Angular官方文件
Now, you just have to filter your post in your nodejs controller: 现在,您只需要在nodejs控制器中过滤帖子即可:
router.get('/posts', function(req, res) {
let query = {};
if(typeof req.query.user_id != 'undefined'){
query['createdBy'] = req.query.user_id // supposing that 'createdBy' is where you store the user id's in post scheme
}
post.find(query).exec(function(err, posts) {
if (err) {
console.log("ERROR FETCHING POSTS!!");
} else {
res.json(posts);
}
});
});
If the user_id
query param is not provided the post.find
function will return all posts, if it is provided will return all the posts created by that user. 如果未提供user_id
查询参数,则post.find
函数将返回所有帖子,如果提供了该参数,则将返回该用户创建的所有帖子。 Hope this help. 希望能有所帮助。
在跳入代码之前,请完成本教程。
https://angular-2-training-book.rangle.io/handout/http/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.