简体   繁体   English

Angular2中的Promise和Arrow函数

[英]Promise and Arrow Function in Angular2

I am new to angular and it may sound silly but I didn't get how this code works 我是新手,可能听起来很傻,但是我不明白这段代码的工作原理

this.ms.getList().then((hl) => { this.HeroesList = hl; });

I called the service method, on success what it returns ? 我称之为服务方法,成功后返回什么?

Secondly, how this arrow function got the array of heroes that my service has to return and then assigning the array to my component variable , 其次,此箭头函数如何获取服务必须返回的英雄数组,然后将其分配给组件变量,

My Component Code : 我的组件代码:

constructor(private ms: myService) {
  }
  ngOnInit() {
    this.ms.getList().then((hl) => { this.HeroesList = hl; });
  }

And here is the service : 这是服务:

import { Injectable } from '@angular/core'
import { Hero } from './hero'
import { HeroesList } from './heroesList'
@Injectable()
export class myService {
    heroes: Hero[];
    getList(): Promise<Hero[]> {
        return Promise.resolve(HeroesList);//when success, return the list 
    }

}

It might be easier to understand if you look at how the TypeScript is transpiled to JavaScript (ES5). 如果您看一下如何将TypeScript转换为JavaScript(ES5),可能会更容易理解。

Your TypeScript: 您的TypeScript:

this.ms.getList().then((hl) => { this.HeroesList = hl; });

Transpiled to JavaScript: 转换为JavaScript:

this.ms.getList().then(function(hl) { 
    this.HeroesList = hl; 
});

The Promise .then() function accepts two callback functions, one for a success callback and one for an error callback. Promise .then()函数接受两个回调函数,一个用于成功回调,另一个用于错误回调。 You're only using the success callback. 您仅使用成功回调。 Therefore, when .then() is executed on your Promise, if your Promise is successful, it will callback to your defined success function. 因此,在Promise上执行.then()时,如果Promise成功,它将回调到您定义的成功函数。 Your defined success function then sets your service variable to the resolved result of your Promise. 然后,您定义的成功函数会将您的服务变量设置为Promise的已解决结果。

当承诺解决后,它将返回heroeslist(即组件中的h1),然后起作用。

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

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