Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

q.all for angular2 observables

Tags:

is there something like q.all to resolve all http api requests in angular2?

In angular1, I can do something like this:

var promises = [api.getA(),api.getB()]; $q.all(promises).then(function(response){     // response[0]  --> A     // response[1]  --> B }) 

In angular2, the http module returns Observable,

api.getA().subscribe(A => {A}) api.getB().subscribe(B => {B}) 

But I want to resolve A and B together, then do something.

like image 359
kdu Avatar asked May 11 '16 19:05

kdu


People also ask

Which is better promise or observable?

The biggest difference is that Promises won't change their value once they have been fulfilled. They can only emit (reject, resolve) a single value. On the other hand, observables can emit multiple results. The subscriber will be receiving results until the observer is completed or unsubscribed from.

What is difference between promise and observable in Angular?

Promises deal with one asynchronous event at a time, while observables handle a sequence of asynchronous events over a period of time. Emit multiple values over a period of time. Emit a single value at a time. Are lazy: they're not executed until we subscribe to them using the subscribe() method.

What is .subscribe in Angular?

Normally Subscription means an arrangement to receive something. Similarly, in Angular applications Observables will be connected to observers and whenever they observe a new value or change in data, they will execute code with the help of Subscription and all the subscribed components will receive the updated outcome.

Is observable asynchronous?

An observable produces values over time. An array is created as a static set of values. In a sense, observables are asynchronous where arrays are synchronous. In the following examples, → implies asynchronous value delivery.


1 Answers

You will need the .forkJoin operator for that

Observable.forkJoin([observable1,observable2])        .subscribe((response) => {           console.log(response[0], response[1]);        }); 

You can import the Observable with;

import {Observable} from 'rxjs/Rx'; 
like image 93
eko Avatar answered Sep 26 '22 15:09

eko