【问题标题】:creating a observable function that has an observable inside it [duplicate]创建一个内部有一个可观察对象的可观察函数[重复]
【发布时间】:2020-08-23 03:30:13
【问题描述】:

我正在尝试创建一个可观察函数,该函数使用其中的可观察对象来完成工作。

verifyinteraction(action): Observable<any>{
return this.recaptchaV3Service.execute(action)
  .subscribe((token :any)=>{
    this.http.post(
      'http://127.0.0.1:8000/verify/recaptcha',
      token);
  });

}

verifyinteraction 函数采用 action

然后将此操作传递给recaptchaV3Service

然后订阅该服务,并将该订阅的结果传递给我的服务器,用于工作,然后返回。订阅verifyinteraction 是这两个动作的结果。

但是,当我编写这段代码时,我遇到了这个错误

- error TS2740: Type 'Subscription' is missing the following properties from type 'Observable<any>': _isScalar, source, operator, lift, and 6 more.

 13     return this.recaptchaV3Service.execute(action)
        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 14       .subscribe((token :any)=>{
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
... 
 17           token);
    ~~~~~~~~~~~~~~~~~
 18       });
    ~~~~~~~~~

它了解我所缺少的吗?有人可以帮我解决这个问题吗?

【问题讨论】:

标签: angular function observable angular2-observables


【解决方案1】:

您可以使用 RxJS 高阶映射运算符之一(如 switchMapconcatMap 等 - 差异 here)从一个 observable 映射到另一个。试试下面的

verifyinteraction(action): Observable<any>{
  return this.recaptchaV3Service.execute(action).pipe(
    switchMap((token :any) => 
      this.http.post(
        'http://127.0.0.1:8000/verify/recaptcha',
        token
      );
    )
  );
}

现在订阅调用this.verifyinteraction(action).subscribe(...) 将首先触发this.recaptchaV3Service.execute(action) 函数并使用其中的令牌来触发this.http.post() 调用。

但是看到您正在使用身份验证,我建议您使用 Angular HttpInterceptor 来缓存令牌并将其添加到 HTTP 请求中,而不是手动将其添加到每个请求中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-09
    相关资源
    最近更新 更多