如何将参数从 angular 2 服务传递到节点 js 函数?意思是

How to pass a parameter from angular 2 service to node js function? MEAN

我有一个 posts 集合,每个 post 都有一个 iduserId.

我想查找特定 user 的所有 posts(使用 userId 属性)。 .

这是我的 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());
    }
}

和我的 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);
        }
    });
});

您需要将 query params 发送到后端以便能够在您的 nodejs controllers.In 您的 Angular 服务中过滤它们,您将拥有这样的东西:

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

最后的 URL 会是这样的:/api/posts?user_id=userIdValue。你需要从 '@angular/common/http' 导入 HttpParams 我假设你有 Angular > 4.3,有关 HttpParams 的更多信息,请参阅 Angular Official Doc

现在,您只需在 nodejs 控制器中过滤 post:

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

如果未提供 user_id 查询参数,post.find 函数将 return 所有 post ,如果提供,将 return 所有post 由该用户创建。 希望对您有所帮助。

在进入代码之前完成本教程。

https://angular-2-training-book.rangle.io/handout/http/