【问题标题】:Promise and Arrow Function in Angular2Angular2中的承诺和箭头函数
【发布时间】:2017-08-26 00:38:06
【问题描述】:

我是 Angular 新手,听起来可能很傻,但我不明白这段代码是如何工作的

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

我调用了服务方法,成功后返回什么?

其次,这个箭头函数如何获取我的服务必须返回的英雄数组,然后将数组分配给我的组件变量,

我的组件代码:

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

这里是服务:

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 
    }

}

【问题讨论】:

    标签: angular promise angular-promise


    【解决方案1】:

    如果你看一下 TypeScript 是如何转译成 JavaScript (ES5) 的,可能会更容易理解。

    你的打字稿:

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

    转译为 JavaScript:

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

    Promise .then() 函数接受两个回调函数,一个用于成功回调,一个用于错误回调。您只使用成功回调。因此,当 .then() 在你的 Promise 上执行时,如果你的 Promise 成功,它会回调你定义的成功函数。然后,您定义的成功函数将您的服务变量设置为您的 Promise 的已解决结果。

    【讨论】:

    • h1 是您的回应。
    【解决方案2】:

    当 promise 解决时.. 它返回 herolist,它是组件中的 h1 然后函数。

    【讨论】:

    猜你喜欢
    • 2018-03-19
    • 2019-07-16
    • 1970-01-01
    • 1970-01-01
    • 2017-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多