如何在Angular服务中返回多个异步调用的结果

问题描述:

在AngularJS中,我可以使用return $q.all(promises)向控制器返回承诺。什么是正确的方式来做Angular?我怎样才能将数据返回给组件?如何在Angular服务中返回多个异步调用的结果

我的服务:

import { Injectable } from '@angular/core'; 
import { Http } from '@angular/http'; 
import { Observable } from 'rxjs/Rx'; 

import { Item } from '../item'; 

@Injectable() 
export class GetItemListService { 
    constructor(private http: Http) { } 

    private url1 = 'urlToGetItemList1'; 
    private url2 = 'urlToGetItemList2'; 

    getItemList(): ??? <Item[]> { 
    Observable 
     .forkJoin(
      this.http.get(url1).map(res => res.json()), 
      this.http.get(url2).map(res => res.json()) 
     ) 
     .subscribe(
      data => { 
       // this is the result I want to return to component 
       return data 
      } 
     ) 
    } 
} 
+1

你可以给您所期望的输入和输出是什么一个例子吗?这是非常类似于https://*.com/questions/35608025/promise-all-behavior-with-rxjs-observables – 0mpurdy

+1

[Promise.all行为与RxJS Observables?]可能的重复?(https://*.com/questions/35608025/promise-all-behavior-with-rxjs-observables) –

+0

在getItemList方法内部返回'Observable.forkJoin'并在你的组件中订阅它。 – echonax

与@ echonax的答案解决它。它在组件中返回Observable.forkJoinsubscribe

服务:

getItemList(): Observable <Item[]> { 
    return Observable 
     .forkJoin(
      this.http.get(url1).map(res => res.json()), 
      this.http.get(url2).map(res => res.json()) 
     ) 
    } 

组件:

ngOnInit(): void { 
     this.getItemListService.getItemList() 
     .subscribe(data => { 
      console.log(data) 
     }) 
    } 
+0

定时器到期时,您可以接受您自己的答案;) – echonax