Reputation: 1499
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
}
)
}
}
Upvotes: 0
Views: 59
Reputation: 1499
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)
})
}
Upvotes: 1