Angular 2 - 同时根据不同的上下文发出多个 HTTP get 请求?
Angular 2 - Make multiple HTTP get request based on different context at same time?
我的 REST 调用服务有不同的 url 上下文来获取不同的数据。我想同时发出 HTTP get 请求并将响应映射到三个不同的下拉列表。
我的代码:
protected getCodes1(): string {
const apiConfig = 'http://www.example.com/context1'; (need to change the context based on parameter)
if (!uri) {
throw new Error('Missing API);
}
return uri;
}
protected getCodes2(): string {
const apiConfig = 'http://www.example.com/context2'; (need to change the context based on parameter)
if (!uri) {
throw new Error('Missing API);
}
return uri;
}
protected getCodes3(): string {
const apiConfig = 'http://www.example.com/context3'; (need to change the context based on parameter)
if (!uri) {
throw new Error('Missing API);
}
return uri;
}
我的 HTTP 调用:
const getCodesList1 = getCodes1();
const getCodesList2 = getCodes2();
const getCodesList3 = getCodes3();
this.http.get('getCodeList1'),
this.http.get('anotherurl'),
this.http.get('anotheranotherurl'),
(response1, response2, response3) => {
//do something to put them all together
//return a single object
}
).subscibe(finalObject => ...)
我没有得到正确的回应。请给我一个线索来得到这些东西..感谢一些线索..
检查 forkJoin
或 mergeMap
来自 RxJS
的运算符
示例:
ngOnInit() {
let character = this.http.get('https://swapi.co/api/people/1');
let characterHomeworld = this.http.get('http://swapi.co/api/planets/1');
forkJoin([character, characterHomeworld]).subscribe(results => {
// results[0] is our character
// results[1] is our character homeworld
results[0].homeworld = results[1];
this.loadedCharacter = results[0];
});
}
我的 REST 调用服务有不同的 url 上下文来获取不同的数据。我想同时发出 HTTP get 请求并将响应映射到三个不同的下拉列表。
我的代码:
protected getCodes1(): string {
const apiConfig = 'http://www.example.com/context1'; (need to change the context based on parameter)
if (!uri) {
throw new Error('Missing API);
}
return uri;
}
protected getCodes2(): string {
const apiConfig = 'http://www.example.com/context2'; (need to change the context based on parameter)
if (!uri) {
throw new Error('Missing API);
}
return uri;
}
protected getCodes3(): string {
const apiConfig = 'http://www.example.com/context3'; (need to change the context based on parameter)
if (!uri) {
throw new Error('Missing API);
}
return uri;
}
我的 HTTP 调用:
const getCodesList1 = getCodes1();
const getCodesList2 = getCodes2();
const getCodesList3 = getCodes3();
this.http.get('getCodeList1'),
this.http.get('anotherurl'),
this.http.get('anotheranotherurl'),
(response1, response2, response3) => {
//do something to put them all together
//return a single object
}
).subscibe(finalObject => ...)
我没有得到正确的回应。请给我一个线索来得到这些东西..感谢一些线索..
检查 forkJoin
或 mergeMap
来自 RxJS
示例:
ngOnInit() {
let character = this.http.get('https://swapi.co/api/people/1');
let characterHomeworld = this.http.get('http://swapi.co/api/planets/1');
forkJoin([character, characterHomeworld]).subscribe(results => {
// results[0] is our character
// results[1] is our character homeworld
results[0].homeworld = results[1];
this.loadedCharacter = results[0];
});
}