0

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
            }
        )
  }
}
vincentf
  • 1,419
  • 2
  • 20
  • 36
  • 1
    can you give an example of what you expect as input and output? This is very similar to https://stackoverflow.com/questions/35608025/promise-all-behavior-with-rxjs-observables – 0mpurdy Jul 27 '17 at 10:01
  • 1
    Possible duplicate of [Promise.all behavior with RxJS Observables?](https://stackoverflow.com/questions/35608025/promise-all-behavior-with-rxjs-observables) – Yury Tarabanko Jul 27 '17 at 10:04
  • return the `Observable.forkJoin` inside `getItemList` method and subscribe to it inside your component. – eko Jul 27 '17 at 10:18

1 Answers1

1

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)
        })
  }
vincentf
  • 1,419
  • 2
  • 20
  • 36