在导航到另一个页面之前,我需要等待完成两个嵌套的可观测值。我不知道什么是最好的方法来做到这一点,因为它们是嵌套的,因此我有同步问题在我的角度应用程序。我的认证服务正在设置可观测值。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()方法,当它完成时,我想导航到另一个实例。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时,可观察到的数据仍在运行。有什么好主意吗?提前谢谢。
发布于 2017-09-15 10:39:55
问题是,您只是在getIdentity()中调用getIdentity(),这并不能使两个可观察的结果连续进行。
相反,您需要返回可观察到的对象,而不是订阅对象,并使用switchMap。
getIdentity
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将切换到第二个可观察到的位置,并在完成第一个任务时返回它。
https://stackoverflow.com/questions/46237390
复制相似问题