简体   繁体   English

在Angular2中,如何返回服务值?

[英]In Angular2, how are service values returned?

I'm following along with the tutorial instructions for Angular2 here: https://angular.io/docs/ts/latest/tutorial/toh-pt4.html 我在这里跟随Angular2的教程说明: https ://angular.io/docs/ts/latest/tutorial/toh-pt4.html

At one point, it notes that to return the service's promise information back to the component, the following syntax is required: 有一点,它指出要将服务的承诺信息返回给组件,需要以下语法:

getHeroes() {
  this._heroService.getHeroes().then(heroes => this.heroes = heroes);
}

I'm trying to understand exactly what's happening here, though I'm new to Angular2 and TypeScript. 我试图准确理解这里发生了什么,虽然我是Angular2和TypeScript的新手。 The documentation says: 文件说:

Our callback sets the component's heroes property to the array of heroes returned by the service. 我们的回调将组件的英雄属性设置为服务返回的英雄数组。

I'm confused about what's going on in the parentheses, and specifically, where the final "heroes" is coming from. 我对括号中发生的事情感到困惑,特别是最终的“英雄”来自哪里。 The service, so far as I can tell, doesn't return "heroes." 据我所知,这项服务不会归还“英雄”。 Instead it imports and returns HEROES from mock-heroes, which itself uses the Heroes interface and returns the HEROES array. 相反,它从mock-heroes导入并返回HEROES,后者本身使用Heroes接口并返回HEROES数组。 I don't see "heroes" (lower case) in any of this. 在任何一个中我都看不到“英雄”(小写)。

Is "heroes" being created on the fly? “英雄”是在飞行中创造出来的吗? Can someone explain in a little more detail what each part of: 有人可以更详细地解释每个部分:

heroes => this.heroes = heroes

does? 呢? Thanks so much. 非常感谢。

The first thing to bear in mind is that the method heroService.getHeroes() does not return heroes, but a promise that will eventually resolve, returning a list of heroes: 要记住的第一件事是,方法heroService.getHeroes()不会返回英雄,而是一个最终会解决的承诺,返回一个英雄列表:

getHeroes() {
    return Promise.resolve(HEROES);
}

Lets then dissect a bit this line of code: 让我们解释一下这行代码:

this._heroService.getHeroes().then(heroes => this.heroes = heroes);

This could also have been written in the following way: 这也可以用以下方式编写:

this._heroService.getHeroes().then(function(heroesFromPromise) {
    this.heroes = heroesFromPromise;
});

This means, call the _heroService.getHeroes() method, which returns a promise. 这意味着,调用_heroService.getHeroes()方法,该方法返回一个promise。 When the promise resolves, the callback inside then is called with the result of the promise. 当承诺解决,里面的回调then调用与承诺的结果。

When that happens execute the callback is called that takes the output of the promise ( heroesPromise ), and assigns it to the this.heroes member variable. 当发生这种情况时,执行调用回调,该回调接受promise( heroesPromise )的输出,并将其分配给this.heroes成员变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM