我正在尝试创建一个可观察函数,该函数使用其内部的可观察对象进行工作。
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 });
~~~~~~~~~
对我所缺少的东西有了解吗?有人可以帮我清理一下吗?
答案 0 :(得分:2)
您可以使用RxJS高阶映射运算符之一(例如switchMap
,concatMap
等-差异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请求中,而不是手动将令牌添加到每个请求中。