在我的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数组.然后我需要用这两个数组进行一些登录.
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;
}
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];
}
);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。