在我的 Angular 2 应用程序中,我有如下后端服务。
getUserInterests() {
return this.http.get('http://localhost:8080/test/selections').map((res: Response) => res.json());
}
调用此服务后,我想在上一个服务成功时调用另一个服务。
第二次服务
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数组。然后我需要使用这两个数组进行一些登录。
已编辑
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 文件中使用以下内容来调用该服务。
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];
}
);
}
}
但这会在控制台日志中给出以下错误。
ORIGINAL EXCEPTION: TypeError: this.dataService.getSelectionList is not a function
如有任何建议,我们将不胜感激。
最佳答案
您需要利用 flatMap
运算符在前一个请求完成后调用一个请求:
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());
}
);
订阅此数据流时,您只会收到上次请求的结果。
您可以使用 Observable.forkJoin
方法返回两者。这是一个示例:
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];
}
);
关于javascript - Angular 2 : Two backend service calls on success of first service,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45732873/