【问题标题】:Observable - Subscribe doesn't receive expected value可观察 - 订阅没有收到预期值
【发布时间】:2021-09-12 09:52:24
【问题描述】:

我创建了一个包含以下方法的服务:

public getSomething(): Observable<MyObject> {
    if (this.myObject) {
      return of(this.myObject); #
    } else {
      return this.myService.DoIt().pipe(
        switchMap((result) => {
          if (result) {
            return this.getObject();  !!!!
          } else {          
            const myObject = new MyObject('Something');
            return of(myObject); #
          }
        }),
        catchError((error) => {
          return this.handleError(error);
        })
      );
    }
  }
  private getObject(): Observable<MyObject> {
    const tempresult = this._http.get<MyObject>({
      endpoint: '/something'
    });
    return tempresult.pipe(
      map((result) => {
        this.myObject = MyObject.fromJson(result);
        return this.myObject;
      })
    );
  }

在组件中,将调用“getSomething”方法,使用:

this.someService.getSomething().subscribe((result) => {
      result -> The subscribe never contains the data of the 'return this.getObject();'
    });

标有 # 的行正在返回正确的数据,但是 !!!!标记的行从不返回订阅中的值。所以显然我做错了什么,但我找不到解决方案。我希望'return this.getObject(); 的值' 在某些情况下会导致订阅。

你能指出我正确的方向吗?我认为这个问题是由当前的管道结构引起的 -> 管道需要返回 Observable。

【问题讨论】:

  • 我没有发现任何明显的问题。你确定this.myService.DoIt() 发出true
  • 在使用断点时,代码确实命中了'return this.getObject();',但订阅没有收到该值。
  • 我猜this._http.get() 可能会抛出一个被catchError 捕获的错误(也许它会抑制错误)?如果没有可重现的演示,很难给出任何建议。

标签: angular rxjs rxjs-observables


【解决方案1】:

下面这行的一个原因:

return this.getObject();

不返回任何数据是例程 getObject() 包含一个 HTTP 请求并返回一个 observable,需要订阅才能在服务器上执行请求并返回 来自可观察对象的发射值。

我会推荐以下内容:

this.getObject().subscribe(res => 
{
    return of(res);
});

【讨论】:

  • 不不,这行不通。从 subscribe 处理程序返回一个值不会做任何事情。
  • 我经常将 subscribe() 用于 http 请求,它总是返回一个值。无论如何,这是一个建议。也许您可以重构代码以仅使用一级 pipe() 运算符。
猜你喜欢
  • 2018-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-21
  • 1970-01-01
  • 1970-01-01
  • 2018-07-28
相关资源
最近更新 更多