【问题标题】:Observable carry a object or a stream of objects?Observable 携带一个对象还是一个对象流?
【发布时间】:2020-07-31 07:33:25
【问题描述】:

Observable 是否有一系列书籍或只有一个书籍对象?

 allBooks$: Observable<Books[]>
    
    getBooks() {
      this.allBooks$ = this.bookService.getBooksFromStore();
    }
    
    ngOnInit() {
     this.getBooks();
    }

【问题讨论】:

  • 这意味着getBooks()函数将返回一个Observable,其中Observable中的每个项目都是Books[],这意味着可观察对象中的每个项目都将是一个@数组987654328@ 个对象。
  • 谢谢palaѕн 现在我明白了

标签: java data-structures time-complexity


【解决方案1】:

我想这会对你有所帮助。

getBooksFromStore(): Observable<Books[]> {
 return this.http.get<Books[]>(this.bookUrl);
}

上述方法将返回Observable&lt;Books[]&gt;

第 2 步:在我们的组件中,我们将创建一个属性。

allBooks$: Observable<Books[]>

getBooks() {
  this.allBooks$ = this.bookService.getBooksFromStore();
}

ngOnInit() {
 this.getBooks();
}

你也可以参考这个:https://www.concretepage.com/angular-2/angular-observable-example

【讨论】:

    【解决方案2】:

    //In Service you will configure API call:
    
    getBooksFromStore(): Observable < Books[] > {
      return this.http.get < Books[] > (this.bookUrl);
    }
    
    //In Component (you will have to subscribe to the Observable same as you do using 'then' in Promises):
    
    ngOnInit() {
      this.bookService.getBooksFromStore().subscribe({
        next: (response) => {
          this.books = response;
        }
      });
    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-27
      • 1970-01-01
      • 2012-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多