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

问题描述

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

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高阶映射运算符之一(例如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请求中,而不是手动将令牌添加到每个请求中。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...