角2:第一个服务的成功两个后端服务电话 [英] Angular 2: Two backend service calls on success of first service
问题描述
在我的角2应用程序我有后端服务如下图所示。
In my Angular 2 app I have backend service as below.
getUserInterests() {
return this.http.get('http://localhost:8080/test/selections').map((res: Response) => res.json());
}
在调用这个服务后,我想呼吁previous一个成功的另一项服务。
After calling this service I want to call another service on success of previous one.
第二服务
let params: URLSearchParams = new URLSearchParams();
params.set('access_token', localStorage.getItem('access_token'));
return this.http.get('http://localhost:8080/user/selections', { search: params }).map((res: Response) => res.json());
这两种服务分别返回两个JSON阵列。然后,我需要做一些与登录这两个数组。
These two services separately return two JSON Arrays. Then I need to do some login with these two arrays.
EDITED
service.ts
getUserInterests() {
return this.http.get('http://localhost:8080/test/selections').map((res: Response) => res.json());
}
getSavedSelections() {
let params: URLSearchParams = new URLSearchParams();
params.set('access_token', localStorage.getItem('access_token'));
return this.http.get('http://localhost:8080/interest/user/selections', { search: params }).map((res: Response) => res.json());
}
getSelectionList() {
var obs = this.getUserInterests().flatMap(
(interests) => {
return Observable.forkJoin([
Observable.of(interests),
this.getSavedSelections()
]);
}
);
return obs;
}
然后,我用我的其他文件的TS下面来调用服务。
Then I am using following in my other ts file to call the service.
export class InterestsComponent {
private interests;
private saved_interests;
constructor(private dataService: DataService) {
this.dataService.getSelectionList().subscribe(
(result) => {
var interests = result[0];
var selections = result[1];
}
);
}
}
但是,这给予以下的控制台日志错误。
But this give following error on console log.
ORIGINAL EXCEPTION: TypeError: this.dataService.getSelectionList is not a function
任何建议都AP preciated。
Any suggestions are appreciated.
推荐答案
您需要利用 flatMap
运营商调用完成previous一个接一个要求:
You need to leverage the flatMap
operator to call one request after the previous one completed:
this.service.getUserInterests().flatMap(
(interests) => {
let params: URLSearchParams = new URLSearchParams();
params.set('access_token', localStorage.getItem('access_token'));
return this.http.get('http://localhost:8080/user/selections', {
search: params
}).map((res: Response) => res.json());
}
);
当订阅该数据流,你只会收到的最后一个请求的结果。
When subscribing to this data flow, you will only receive the result of the last request.
您可以使用 Observable.forkJoin
方法返回两者。这里有一个例子:
You could use the Observable.forkJoin
method to return both. Here is a sample:
var obs = this.service.getUserInterests().flatMap(
(interests) => {
return Observable.forkJoin([
Observable.of(interests),
this.service.getUserSelections()
]);
}
);
obs.subscribe(
(result) => {
var interests = result[0];
var selections = result[1];
}
);
这篇关于角2:第一个服务的成功两个后端服务电话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!