Angular2 订阅嵌套

发布于 2022-09-05 09:17:34 字数 1028 浏览 19 评论 0

问题是这样出现的: 从博客列表进入博客详情的时候, 从url中解析id, 然后根据id获得博客全部信息.
虽然能成功获取到博客, 但是chrome console里会报错, 说Cannot read property 'title' of undefined. 感觉是因为订阅嵌套的原因, 但是不知道应该用什么方式来实现从url获取id然后根据id获取博客本身.

试着并列两个订阅, 一样能运行但是也报错.

// blog-full.component.ts
ngOnInit() {
    this.route.params 
    .subscribe( // 订阅'@angular/route'里的Router的params获取id
      (params: Params) => {
        this.id = params['id'];
        this.blService.getBlog(this.id)
          .subscribe( // 订阅blogService里的getBlog获取博客本身
            (blog:Blog) => {
              this.blog = blog;
              console.warn(this.blog);
            });
      });
}
// blogs.service.ts
getBlog(id: number){
    return this.http.get('https://xxx.example.com/blogs/'+id)
      .map((response:Response) => {
        return response.json().obj;
      })
      .catch((error:Response) => {
        return Observable.throw("error when get one blog");
      });
  }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

信愁 2022-09-12 09:17:34

订阅嵌套不是很优雅,使用rxjs中的mergeMap可以解决你的问题。

具体见:使用rxjs处理多个网络请求

栖迟 2022-09-12 09:17:34

用mergeMap看起来才是正确的方式, 之前嵌套虽然能工作, 但总觉着不是这样的.

// with mergeMap
ngOnInit() {
    this.route.params
      .mergeMap((params: Params) => {
        this.id = params['id'];
        return this.blService.getBlog(this.id);
      })
      .subscribe((blog) => {
        this.blog = blog;
      });
  }

另外console里报错的解决方式是将{{blog.content}}加个问号{{blog?.content}}

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文