Synchronous functions - in Angular

JaSHin picture JaSHin · Jan 17, 2016 · Viewed 19.6k times · Source

I need to reach in the Angular synchronous functions (that the other waiting for the end of the first).

For example, I have two providers (MenuProvider and ShopProvider).

MenuProvider has a method :

getMenuItemsForCurrentShop()

that over HTTP retrieves the menu items for the current shop.

ShopProvider has a method:

setCurrentShopById(idShop:number)

that sets via HTTP which the shop is currently used.

I need to "getMenuItemsForCurrentShop()" called after "setCurrentShopById(idShop:number)". Ideally without callback.

Answer

vittore picture vittore · Jan 17, 2016

There is some difference in a way how you are going to handle this situation in angular1 vs angular2.

Typical approach for angular1 is to use promises, i e your first provider method will return promise , and all you do is call .then method on the return object, passing callback function that will accept result of first method and you will call second method inside it.

For an example of this technique you can see @Pankaj answer.

Angular2 is different in this sense as it started using ReactiveExtensions library ( rx.js ). So every component likely to return Observable<Someth> which provide a lot more methods to work with it compared to promises. (You still can use promises approach with observables though).

For an example of how to use angular2\http module see another question: Angular 2: How to use/import the http module?

Also take a look at http module docs in angular2

ShopApi.ts:

import {Injectable, bind} from 'angular2/di';
import {Http, Headers} from 'angular2/http';
import {Observable} from 'rx'; 
   
@Injectable()
export class ShopApi {
  constructor(public http: Http) {
  }

  setCurrentShopById(idShop:Number) {
    return this.http.get('http://myservice.com/current/shop/', idShop)
    .toRx()
    .map(res => res.json());
  }

  getMenuItemsForCurrentShop() {
    return this.http.get('http://myservice.com/current/shop/items')
    .toRx()
    .map(res => res.json());
  }
}