我如何将 promise 与 observable 融合在一起?
How do I blend a promise with an observable?
我在 promises 和 observables 上遇到了麻烦。我有一些 http 请求,它们是在使用 promises 的包中定义的。在我的其余代码中,我将 observables 用于各种事情,包括其他 http 调用。在一个特定的部分中,我正在检查用户的不记名令牌是否已过期,如果已过期,我将获得一个新令牌,然后继续调用的其余部分。
if (!token || token.exp < Math.round((new Date()).getTime() / 1000)) {
from(this._store.refreshBearerToken())
.pipe(flatMap(resp => {
let newToken = resp.data;
newToken.exp = (new Date()).getTime() / 1000 + newToken.expires_in;
localStorage.setItem('token', JSON.stringify(newToken))
options = options || {};
options.headers = new HttpHeaders({
"Authorization": `${newToken.token_type} ${newToken.access_token}`,
"Content-Type": "application/json"
});
return this._http$.request<T>(method, url, options as Object).pipe(share());
}));
}
不记名令牌方法:
async refreshBearerToken() {
const response = await this._q2.sources.requestExtensionData({
route: "refreshBearerToken"
});
console.log(response);
return response;
}
因为 this._store.refreshBearerToken
return 是一个承诺,所以我将调用包装在 from
中以将其转换为可观察的。这编译但是当它运行时我得到 "Cannot read property 'pipe' of undefined"。
如何将此 promise 转换为可观察对象,以便我可以刷新令牌,然后继续调用的其余部分?
编辑:
我正在通过 import { Observable, from } from "rxjs";
导入 from
。
所以,我认为错误来自 .pipe(flatMap(resp =>...
行,但我错了。错误来自调用此方法的方法。
GetInitialLinkList(): Observable<Institution[]>
{
let base = { 'MemberId': localStorage.getItem('memberId') };
let ins = localStorage.getItem("initialInstitutionList");
if (ins)
{
return of(JSON.parse(ins));
}
return this._settingsService.get().pipe(
flatMap(settings =>
{
this._settings = settings;
return this._api.request<Institution[]>("Post", `${this._settings.mea}/GetInitialLinkList`, { body: base })
.pipe(
retry(1),
catchError(this.handleError)
)
.pipe(flatMap(instList =>
{
localStorage.setItem("initialInstitutionList", JSON.stringify(instList));
return of(instList);
}))
}));
}
并且正在我的组件中订阅:
private GetLinkList()
{
this.showWaiting.emit(true);
this._data.GetInitialLinkList().subscribe((result) =>
{
this.initialList = result;
this.showWaiting.emit(false);
});
}
根据 Brandon 所说的(我忘了 return /facepalm...)我添加了 return 所以我有 return from(this._store.refreshBearerToken())
将我的错误更改为
ERROR Error Code: undefined
Message: You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.
defaultErrorLogger @ core.js:6014
您能否显示实际错误以及代码中发生错误的行?还显示导入的位置和方式 from
.
我注意到您的代码片段没有 return 它通过 from(...).pipe(...)
构建的可观察对象,也没有订阅它。它可能有助于显示您的代码实际如何使用此可观察对象。
我在 promises 和 observables 上遇到了麻烦。我有一些 http 请求,它们是在使用 promises 的包中定义的。在我的其余代码中,我将 observables 用于各种事情,包括其他 http 调用。在一个特定的部分中,我正在检查用户的不记名令牌是否已过期,如果已过期,我将获得一个新令牌,然后继续调用的其余部分。
if (!token || token.exp < Math.round((new Date()).getTime() / 1000)) {
from(this._store.refreshBearerToken())
.pipe(flatMap(resp => {
let newToken = resp.data;
newToken.exp = (new Date()).getTime() / 1000 + newToken.expires_in;
localStorage.setItem('token', JSON.stringify(newToken))
options = options || {};
options.headers = new HttpHeaders({
"Authorization": `${newToken.token_type} ${newToken.access_token}`,
"Content-Type": "application/json"
});
return this._http$.request<T>(method, url, options as Object).pipe(share());
}));
}
不记名令牌方法:
async refreshBearerToken() {
const response = await this._q2.sources.requestExtensionData({
route: "refreshBearerToken"
});
console.log(response);
return response;
}
因为 this._store.refreshBearerToken
return 是一个承诺,所以我将调用包装在 from
中以将其转换为可观察的。这编译但是当它运行时我得到 "Cannot read property 'pipe' of undefined"。
如何将此 promise 转换为可观察对象,以便我可以刷新令牌,然后继续调用的其余部分?
编辑:
我正在通过 import { Observable, from } from "rxjs";
导入 from
。
所以,我认为错误来自 .pipe(flatMap(resp =>...
行,但我错了。错误来自调用此方法的方法。
GetInitialLinkList(): Observable<Institution[]>
{
let base = { 'MemberId': localStorage.getItem('memberId') };
let ins = localStorage.getItem("initialInstitutionList");
if (ins)
{
return of(JSON.parse(ins));
}
return this._settingsService.get().pipe(
flatMap(settings =>
{
this._settings = settings;
return this._api.request<Institution[]>("Post", `${this._settings.mea}/GetInitialLinkList`, { body: base })
.pipe(
retry(1),
catchError(this.handleError)
)
.pipe(flatMap(instList =>
{
localStorage.setItem("initialInstitutionList", JSON.stringify(instList));
return of(instList);
}))
}));
}
并且正在我的组件中订阅:
private GetLinkList()
{
this.showWaiting.emit(true);
this._data.GetInitialLinkList().subscribe((result) =>
{
this.initialList = result;
this.showWaiting.emit(false);
});
}
根据 Brandon 所说的(我忘了 return /facepalm...)我添加了 return 所以我有 return from(this._store.refreshBearerToken())
将我的错误更改为
ERROR Error Code: undefined
Message: You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.
defaultErrorLogger @ core.js:6014
您能否显示实际错误以及代码中发生错误的行?还显示导入的位置和方式 from
.
我注意到您的代码片段没有 return 它通过 from(...).pipe(...)
构建的可观察对象,也没有订阅它。它可能有助于显示您的代码实际如何使用此可观察对象。