Synchronous functions - in Angular

20,532

Solution 1

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

Solution 2

You shouldn't think of to make synchronous ajax to solve your problem, as they make browser hangs(bad user experience) & also stop execution of code for a while. May be in future sync ajax are not going to be supported by any browser.

You need to follow asynchronous way only to deal with this problem, using promise pattern would help you to solve your problem. You should call other function setCurrentShopById in the success function of getMenuItemsForCurrentShop .then function.

I assumed getMenuItemsForCurrentShop function has returned promise object.

this.getMenuItemsForCurrentShop().then((response) => {
    this.setCurrentShopById(response.artists.items);
});
Share:
20,532
JaSHin
Author by

JaSHin

Updated on June 23, 2020

Comments

  • JaSHin
    JaSHin over 3 years

    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.