【问题标题】:How to pass a parameter from angular 2 service to node js function? MEAN如何将参数从 Angular 2 服务传递到节点 js 函数?意思是
【发布时间】:2018-04-03 09:31:34
【问题描述】:

我有一个 posts 集合,每个帖子都有一个 iduserId

我想查找特定用户的所有帖子(使用 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);
        }
    });
});

【问题讨论】:

  • 你还在纠结这个吗??
  • 是的...任何想法):?
  • 你能添加你的猫鼬帖子架构吗?

标签: javascript angularjs node.js mongoose mean-stack


【解决方案1】:

在开始编写代码之前完成本教程。

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

【讨论】:

    【解决方案2】:

    您需要将 query params 发送到后端,以便能够在您的 nodejs 控制器中过滤它们。在您的 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 控制器中过滤您的帖子:

    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 函数将返回所有帖子,如果提供,则返回该用户创建的所有帖子。 希望对您有所帮助。

    【讨论】:

    • 谢谢兄弟...你能给我一个活生生的例子的链接吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-10
    • 1970-01-01
    • 2020-09-14
    • 2017-07-23
    • 2019-05-26
    • 1970-01-01
    相关资源
    最近更新 更多