3

我需要在 Angular 同步函数中达到(即对方等待第一个结束)。

例如,我有两个提供商(MenuProvider 和 ShopProvider)。

MenuProvider 有一个方法:

getMenuItemsForCurrentShop()

通过 HTTP 检索当前商店的菜单项。

ShopProvider 有一个方法:

setCurrentShopById(idShop:number)

通过商店当前使用的 HTTP 设置。

我需要在“setCurrentShopById(idShop:number)”之后调用“getMenuItemsForCurrentShop()”。理想情况下没有回调。

4

2 回答 2

3

在 angular1 和 angular2 中处理这种情况的方式有所不同。

angular1 的典型方法是使用 Promise,即您的第一个提供程序方法将返回 Promise,您所做的就是.then在返回对象上调用方法,传递callback将接受第一种方法结果的函数,然后您将在其中调用第二种方法。

有关此技术的示例,您可以查看@Pankaj 答案。

Angular2 在这个意义上是不同的,因为它开始使用 ReactiveExtensions 库(rx.js)。因此,与 Promise 相比,每个可能返回的组件Observable<Someth>都提供了更多的方法来使用它。(不过,您仍然可以对可观察对象使用 Promise 方法)。

有关如何使用 angular2\http 模块的示例,请参见另一个问题:Angular 2: How to use/import the http module?

还可以查看angular2中的http 模块文档

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

于 2016-01-17T15:47:33.030 回答
2

您不应该考虑制作同步 ajax 来解决您的问题,因为它们会使浏览器挂起(糟糕的用户体验)并且还会停止执行代码一段时间。可能将来sync任何浏览器都不会支持ajax。

您只需要遵循异步方式来处理此问题,使用承诺模式将帮助您解决问题。您应该在.then 函数setCurrentShopById的成功函数中调用其他函数。getMenuItemsForCurrentShop

我假设getMenuItemsForCurrentShop函数返回了 promise 对象。

this.getMenuItemsForCurrentShop().then((response) => {
    this.setCurrentShopById(response.artists.items);
});
于 2016-01-17T15:26:44.807 回答