简体   繁体   中英

How do I return the results of multiple asynchronous calls in Angular service

In AngularJS, I can use return $q.all(promises) to return a promise to controllers. What's the right way to do it in Angular? How can I return data to components ?

My Service:

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

Resolved it with @echonax's answer. Return Observable.forkJoin and subscribe it in component.

Service:

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

Component:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM