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

时间:2017-07-27 09:59:59

标签: angular

在AngularJS中,我可以使用return $q.all(promises)向控制器返回一个承诺。在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 个答案:

答案 0 :(得分:1)

用@ 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)
        })
  }