javascript - 如何在 Angular 中调用用 => 定义的函数?

标签 javascript angular

从这里:https://angular.io/tutorial/toh-pt4 - hero.component.ts

getHeroes(): void {
  this.heroService.getHeroes()
      .subscribe(heroes => this.heroes = heroes);
}

我明白这个 heroes => this.heroes = Heroes 翻译如下:

f( heroes )
{
   return this.heroes = heroes;
}

这里是否隐含了return

我想了解这个内部函数是从哪里调用的。谁在叫它?

最佳答案

在您提供的示例代码中,要返回英雄列表,我们必须这样写

getHeroes(): Hero[] {  
this.heroService.getHeroes()
      .subscribe(heroes => ({heroes : heroes}));
}

上面的箭头功能将转换为

f( heroes )
{
   return this.heroes = heroes;
}

否则,您提供的代码只是对 this.heros 变量进行赋值,因此 return 语句不适用,并且箭头函数将转换为

f( heroes )
{
   this.heroes = heroes;
}

箭头函数的进一步解释

箭头函数与函数表达式一样,可用于返回对象字面量表达式。唯一需要注意的是,主体需要用括号括起来,以便区分块和对象(两者都使用大括号)。

示例

//ES5
var setNameIdsEs5 = function setNameIds(id, name) {
  return {
    id: id,
    name: name    
  };
};

// ES6
var setNameIdsEs6 = (id, name) => ({ id: id, name: name });

console.log(setNameIdsEs6 (4, "Kyle"));   // Object {id: 4, name: "Kyle"}

对于常规函数,如果“this”关键字位于对象的方法(属于对象的函数)内,它将引用该对象。在箭头函数中,“this”始终引用其所在函数的所有者。在箭头函数的 return 之前添加 console.log(this) 将返回一个 Window 对象。

示例

// ES5
const brunch = {
 food: 'Dim sum',
 beverage: 'Jasmine tea',
 order: function() {
    return `I'll have the ${this.food} with ${this.beverage} please.`
 }
}
brunch.order(); //"I'll have the Dim sum with Jasmine tea please."
// ES6
const brunch = {
 food: 'Dim sum',
 beverage: 'Jasmine tea',
 order: () => {
    return `I'll have the ${this.food} with ${this.beverage} please.`
 }
}
brunch.order(); //"I'll have the undefined with undefined please."

关于javascript - 如何在 Angular 中调用用 => 定义的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61811090/

相关文章:

javascript - writer.setAttribute 不会触发 View 向下转换

javascript - 将选定的文本扩展为整个单词

javascript - WebGL 在逐像素操作中使用库的速度是否更快?

javascript - 变量无法从订阅方法分配

带有未封闭标签的 Angular HTML 绑定(bind)

javascript - npm run build 出错

javascript - 使用 B2C 的 Javascript/Angular 6 SPA 应用程序中通过 MSAL.JS 注销时出错

javascript - JSX 元素类不支持属性,因为它没有 'props' property.ts(2607)

javascript - 为什么对象的方法中用的是对象名而不是this呢?

angular - 如何将 PrimeIcons 与表格/网格分页器一起使用