订阅时返回。 ...类型“订阅”缺少以下属性

时间:2019-01-07 15:48:38

标签: angular typescript angular6 angular7

我正在订阅Angular服务的响应:

  books: BookModel[] = [];

  constructor(private bookService: BookService) { }

  ngOnInit() {

    this.books = this.getBooks();

  }

  getBooks(): BookModel[] {

    return this.bookService.getByCategoryId(1).subscribe((payload: Payload<GetBooksResponse>) => {

      return payload.result.map((response: GetBooksResponse) => { 

        return {
          id: response.id, 
          title: response.title
        };

      });

    });

  }

当我将return添加到this.bookService,例如return this.bookService时,我得到了错误:

Type 'Subscription' is missing the following properties from type 'BookModel[]': length, pop, push, concat, and 26 more.

如何使用return来完成这项工作?

更新:BookModel:

export interface BookModel {
  id: number;
  title: string;
}

4 个答案:

答案 0 :(得分:4)

您正在尝试将订阅分配到数组中,这就是为什么您会收到以下错误消息:

我使用Observables和异步管道制作了此示例,希望对您有所帮助:

TS:

 /***
   *  books$ Observable is looking to any response
   *  of the method getByCategoryId. It is being displayed with async pipe in the view.
   */
  books$ = this.bookService.getByCategoryId(1);

  books: BookModel[];

  constructor(private bookService: BookService) { }

  ngOnInit() {
    this.getBooks();
  }

  /***
   *  Getbooks method does not return anything, 
   *  after the subscribe, a map is assigning the value to the books propertie
   *  which is in being render in the view without async pipe. 
   */
  getBooks(): void {
    this.bookService.getByCategoryId(1)
      .subscribe((payload: Payload<GetBooksResponse>) => {

        this.books = payload.result.map((response: GetBooksResponse) => {
          return <BookModel>{
            id: response.id,
            title: response.title
          };
        });

      });
  }

HTML:

<div *ngFor="let book of (books$ | async).result">
    {{ book | json }}
</div>

<br/>
<h3> Not Using | async </h3>

<div *ngFor="let book of books">
  {{ book | json }}
</div>

通过以下链接在线尝试:https://stackblitz.com/edit/angular-k9pzmw

如果您问我哪种方法更好,那取决于您。

具有可观察性的异步管道是我的最爱,它仅在视图中显示“哑数据”,但是如果您需要在组件中将此信息用于其他任何用途,则应保留订阅解决方案。

答案 1 :(得分:1)

您需要返回

getBooks(): Observable<BookModole[]> { ... }

然后:

this.getBooks().subscribe(res => { this.books = res; });

答案 2 :(得分:0)

您可以使用of从某些类型的集合中返回新的观察者

https://rxjs-dev.firebaseapp.com/api/index/function/of

答案 3 :(得分:0)

我试图将Subscription保存在typed Observable<T>变量中。只是不必订阅,因为我在HTML中使用了async管道。