gpt4 book ai didi

Angular 2等待嵌套的可观察对象完成

转载 作者:行者123 更新时间:2023-12-05 07:40:19 27 4
gpt4 key购买 nike

在导航到另一个页面之前,我需要等待我的两个嵌套 Observable 完成。我不知道执行此操作的最佳方法是什么,因为它们是嵌套的,因此我的 Angular 应用程序出现了同步问题。Observables 正在我的身份验证服务中设置。authentication.service.ts:

login(username: string, password: string) {
let reqUrl = AppSettings.__USER_TOKEN_URL;
let reqHeaders = this.authConfig.token.headers;
let reqBody = encodeURI(
this.authConfig.token.body
.replace(/{{ username }}/g, username)
.replace(/{{ password }}/g, password));

//
// Get token, then get user identity, if login successfull.
//

return this.http.post(reqUrl, reqBody, reqHeaders)
.map((response) => this.getIdentity(response))
.catch(this.handleErr);
}

private getIdentity(response: Response) {

//
// Get user identity based on token.
//

let body = response.json();
let token = body.access_token;

if (null != token && undefined != token) {
this.authConfig
.identity
.headers
.headers.set('authorization', 'Bearer ' + token);

let reqUrl = AppSettings.__USER_IDENTITY_URL
let reqHeaders = this.authConfig.identity.headers;
let reqbody = this.authConfig.identity.body;

return this.http.post(reqUrl, reqbody, reqHeaders)
.map((response) => this.setUser(response))
.catch(this.handleErr)
.subscribe();
}
}

然后在我的登录组件中,我试图调用服务 login() 方法,当它完成时,我想导航到另一个实例。login.component.ts:

login() {
this.loading = true;
this.authenticationService.login(this.model.username, this.model.password).subscribe(
data => { },
error => { console.log('Error authenticating: ' + error); },
() => { this.router.navigate([this.returnUrl]) });
}

但它不起作用。当 router.navigate 被触发时,Observables 仍在运行。对 Angular 菜鸟有什么想法吗?提前致谢。

最佳答案

问题是您只是在 getIdentity() 中调用 subscribe,这不会使两个可观察对象连续

相反,您需要返回可观察对象而不是那里的订阅对象并使用 switchMap

获取身份:

private getIdentity(response: Response) {

//
// Get user identity based on token.
//

let body = response.json();
let token = body.access_token;

if (null != token && undefined != token) {
this.authConfig
.identity
.headers
.headers.set('authorization', 'Bearer ' + token);

let reqUrl = AppSettings.__USER_IDENTITY_URL
let reqHeaders = this.authConfig.identity.headers;
let reqbody = this.authConfig.identity.body;

return this.http.post(reqUrl, reqbody, reqHeaders)
.map((response) => this.setUser(response))//return observable.
}
}

在登录调用中:

return this.http.post(reqUrl, reqBody, reqHeaders)
.switchMap((response) => this.getIdentity(response))
.catch(this.handleErr);

switchMap 将切换到第二个 observable 并在第一个完成时返回它。

关于Angular 2等待嵌套的可观察对象完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46237390/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com