【问题标题】:Using the rxjs take() with Angular's http [duplicate]使用 rxjs take() 和 Angular 的 http [重复]
【发布时间】:2019-06-05 10:23:33
【问题描述】:

假设我在提供程序中有这样的功能:

getAll(): Observable<CarModel[]> {
    return this.http.get<CarModel[]>(this.carUrl);
}

并且在一个组件中我有一个使用提供者这个功能的功能:

getCars() {
        const that = this;
        this.carService.getAll().subscribe(function(cars) {
            that.factoryService.setCars(cars);
            this.unsubscribe();
        });
    }

是否可以将其替换为使用take 运算符以避免调用unsubscribe() 的函数?

getCars() {
        const that = this;
        this.carService.getAll().take(1).subscribe(function(cars) {
            that.factoryService.setCars(cars);
        });
    }

我想知道当与 Angular 的 Httpclient 方法一起使用时,这是否会产生任何意外或不需要的行为?我从来没有见过这样使用 Angular 的 Httpclient - 这就是我要问的原因。

【问题讨论】:

标签: javascript angular rxjs


【解决方案1】:

请求完成后,HttpClient 在流上调用complete。一个调用完整信号的 Observable 将不再发出任何值,因此任何订阅者都不会再收到任何值。这意味着没有理由取消订阅或将 take 与 http 请求一起使用。

getAll(): Observable<CarModel[]> {
  return this.http.get<CarModel[]>(this.carUrl); // <- Emits once and completes
}

查看文档中的 this 部分。注意:

来自 HttpClient 的 observable 总是发出单个值然后完成,永远不会再次发出。

【讨论】:

    【解决方案2】:

    像你一样,我以前从未见过这样的。

    我曾经将所有的 http 请求 observables 转换为 Promise:

    在 MDN 站点中,您可以找到以下内容: The Promise object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value.

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

    this.carService.getAll()
            .toPromise()
            .then((cars) => {
                that.factoryService.setCars(cars);
            }).catch((error) => {
                console.error(error);
            });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-03
      • 2018-04-09
      • 2018-11-24
      相关资源
      最近更新 更多