定义组件中的可观察对象

时间:2019-01-14 12:39:55

标签: angular angular7

我在Angular 7中具有以下服务方法:

public getTopPosts(): Observable<Payload<PostResponse>> {

  return this.httpClient.get<Payload<PostResponse>>('/top-posts');

}

在组件上,我有:

export class TopPostsComponent implements OnInit {

  posts: PostModel[] = [];

  constructor(private postService: PostService) { }

  ngOnInit() {
    this.getPosts();
  }

  getPosts() {

    this.postService.getTopPosts().subscribe((payload: Payload<PostResponse>) => {

      this.posts = payload.map((response: PostResponse) => { 
        return {
          id: response.id, 
          title: response.title
        };
      });

    });

  }
}

TopPostsComponent中的posts变量不应为:

posts$: Observable<PostModel>[] = []; 

但是然后我得到了错误:

Type '{ id: number; title: string; }[]' is not assignable to type 'Observable<PostModel>[]'.
Type '{ id: number; title: string; }' is missing the following properties from type 'Observable<PostModel>': _isScalar, source, operator, lift, and 6 more."

使用时:

this.posts$ = payload.map((response: PostResponse) => { 
  return {
    id: response.id, 
    title: response.title
  };
});

正确的方法是什么?

1 个答案:

答案 0 :(得分:1)

您无法使用数组初始化可观察对象。

posts$: Observable<PostModel>[] = [];

尝试使用此:

posts$ = this.postService.getTopPosts().pipe(map(items => items.map(item => ({id: item.id, title: item.title}))));`

当然,您可以提取映射到其他方法,以使其更易于阅读。 或者,您可以简单地完全删除映射(为什么要复制ID和标题而不直接使用它们?)。

export class TopPostsComponent implements OnInit {

  posts$: Observable<PostModel[]>;

  constructor(
    private postService: PostService,
  ) { }

  ngOnInit() {
    this.posts$ = this.postService.getTopPosts().pipe(
      map(items => items.map(item => this.responseItemToModel(item)))
    );
  }

  private responseItemToModel(item: PostResponse): PostModel {
    return {
      id: item.id,
      title: item.title,
    };
  }
}