可观察对象类型有两个http.Angular 2中的get调用
Observable type with two http.get calls in Angular 2
在我的ng2服务中,我有一个方法,它有2个http。得到调用。函数看起来像这样:
getInfo(userId: number): any {
this.http
.get(apiUrl, options)
.map(response => response.json())
.subscribe(example => {
this.example.FirstName = example.FirstName;
this.example.LastName = example.LastName;
this.http
.get(`/api/${userId}`)
.map(response => response.json())
.subscribe(example => {
this.example.Street = example.Street;
this.example.City = example.City;
return this.example;
});
});
}
唯一的问题是,在我的组件中,我不能订阅这个函数,因为它不是Observable<Example>
类型。
如果我用Observable<Example>
替换函数的any类型,我得到:
声明类型既不是'void'也不是'any'的函数必须返回一个值
但是我确实返回一个值,在响应之后。
如何做到这一点,而不需要两个独立的函数?
是的,我检查了这个答案:https://stackoverflow.com/a/36712707/3264998
试着把这个作为你的方法体,这是解决这个问题的一种方法。
return this.http
.get(apiUrl, options)
.map(response => response.json())
.flatMap(example => {
this.example.FirstName = example.FirstName;
this.example.LastName = example.LastName;
return this.http
.get(`/api/${userId}`)
.map(response => {
let example =response.json();
this.example.Street = example.Street;
this.example.City = example.City;
return this.example;
});
});
我的解决方案使用rxjs/Rx flatMap:
import {Observable} from 'rxjs/Rx';
ngOnInit() {
const usersId = ['USR001', 'USR003'];
this.doRequest(usersId);
}
doRequest(queryArr, previousObservable = null) {
if (queryArr.length) {
const url = 'api/' + queryArr.shift();
let observable = null;
if (previousObservable) {
observable = previousObservable.flatMap(() => {
return this.http.get(url);
});
} else {
observable = this.http.get(url);
}
return this.doRequest(queryArr, observable);
} else {
return previousObservable;
}
}
相关文章:
- Angular http.get没有'我不喜欢在开头和结尾加方括号的文本文件
- 使用angular$http和django-urlpatters来获得json文件
- 从angular$http获取promise数据
- Angular$http然后解析_.each中的多个调用
- Angular $http 服务不加载 json 文件
- 如何使用Angular$http.jsonp从S3加载JSON文件
- Angular$http.jsonp-服务器don'不接受JSON_CALLBACK
- Angular-$http范围问题
- Angular$http.post未到达服务器
- Angular$http返回数据,但不返回'不适用于范围
- Angular $http not invoking
- Angular http在Phone gap中返回错误,但在浏览器中成功
- 为什么可以't我取消了这个Angular HTTP请求
- Angular$http$资源等价于PDF GET请求
- 在服务中使用Angular$http在ng点击时触发
- 如何使用$q's构造函数语法与Angular$http's配置超时
- Angular http Get Always 返回 ng-click 的状态 0
- 循环遍历 Angular HTTP 请求中的对象,等到响应后再运行下一个循环
- Angular http 返回 $$state 对象
- PHP 和 Angular $http ajax 的问题