创建一个内部有可观察对象的可观察函数

creating a observable function that has an observable inside it

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

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       });
    ~~~~~~~~~

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

您可以使用 RxJS higher-order 映射运算符之一(如 switchMapconcatMap 等 - 差异 here)从一个可观察对象映射到另一个。尝试以下

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 请求中,而不是手动将其添加到每个请求中。