我想在Angular 2中使用Observable时处理异步流。 详细地说,在每个用户的请求之前,我需要获得服务票据,如果该票证有效,用户可以得到适当的响应。因此,我必须在实际请求之前先做http请求,如下所示,我调用名为getServiceTicket()的方法,但是,由于异步流,在我获得有效服务票证之前,执行以下http请求(getDetail)有效的服务票。所以我尝试使用像isServiceTicket这样的标志,但我意识到它并不能保证这两种方法的顺序运行。我试着做一些研究,但我找不到满意的答案。如果有人有这方面的好解决方案,你能提出一些建议吗?
getServiceTicket() {
this.userAuthServie.getServiceTicket().subscribe(
(data: string) => {this.serviceTicket = data; this.isServiceTicket = true;}
);
}
getDetail(id: string) {
this.getServiceTicket();
return this.http.get('https://localhost/detail/' + id + '?ticket=' + this.serviceTicket)
.map( (responseData) => {
return <User>responseData.json();
}
);
}
答案 0 :(得分:0)
您可以更改以下代码:
user:User;
getDetail(id: string) {
this.userAuthServie.getServiceTicket()
.subscribe((data: string) => {
this.serviceTicket = data;
this.isServiceTicket = true;
this.http.get('https://localhost/detail/' + id + '?ticket=' + this.serviceTicket)
.map( (responseData) => {
this.user= <User>responseData.json();
});
});
}
答案 1 :(得分:0)
您可以在第一个函数的subscribe方法的成功部分中放置要运行的第二个函数。
getServiceTicket() {
this.userAuthServie.getServiceTicket().subscribe(
(data: string) => {
this.serviceTicket = data; this.isServiceTicket = true;
this.getDetail(id);
}
);
}
答案 2 :(得分:0)
如果您想等待任何&#34;详细请求之前加载服务票据&#34;执行后,您应该等待服务票据的响应来解决。有多种方法,一种方法可能是将详细信息添加到队列中,或者让getDetails等到加载服务票据。
getServiceTicket() {
// you need to return the observable from service ticket
return this.userAuthServie
.getServiceTicket()
// use map here to only intercept the value.
// remember that you need to subscribe somewhere else
// if called from elsewhere than getDetail
.map((data: string) => {
this.serviceTicket = data;
this.isServiceTicket = true;
return data;
});
}
getDetail(id: string) {
return this.getServiceTicket()
// we switch the observable from ticket to the one from detail using switchMap
.switchMap((data: string) => {
let url = 'https://localhost/detail/' + id + '?ticket=' + this.serviceTicket;
return this.http
.get(url)
.map((responseData) => {
return <User>responseData.json();
});
});
}
}