Angular2 订阅嵌套

问题是这样出现的: 从博客列表进入博客详情的时候, 从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");
      });
  }
阅读 5.7k
2 个回答

用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}}

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进