为了账号安全,请及时绑定邮箱和手机立即绑定

我应该在Angular的类中编写方法作为箭头函数

我应该在Angular的类中编写方法作为箭头函数

犯罪嫌疑人X 2019-08-19 17:23:34
我应该在Angular的类中编写方法作为箭头函数在Angular中,在技术上可以将类方法编写为ES2015箭头函数,但我从未真正见过有人这样做过。以这个简单的组件为例:@Component({   selector: 'sample'})export class SampleComponent {   arrowFunction = param => {     // Do something   };   normalFunction(param) {     // Do something   }}这没有任何问题。有什么不同吗?为什么我应该或不应该使用它?
查看完整描述

3 回答

?
BIG阳

TA贡献1859条经验 获得超6个赞

类箭头函数的一个很好的用例是当你想将一个函数传递给另一个组件并在函数中保存当前组件的上下文时。

@Component({

   template:`
        I'm the parent       <child-component></child-component>

  `})export class PerentComponent{

   text= "default text"
   arrowFunction = param => {
    // Do something
    // let's update something in parent component ( this)

    this.text = "Updated by parent, but called by child"
  };}@Component({

   template:`
        I'm the child component  `})export class ChildComponent{
   @Input() parentFunction;

   ngOnInit(){
      this.parentFunction.()
   }}

 <parent-component></parent-component>

在上面的例子中,child能够调用父组件的函数并且文本将被正确地更新,就好像我只是将父级更改为:

export class PerentComponent{

   text= "default text"
   arrowFunction (){
    this.text = "This text will never update the parent's text property, because `this` will be child component  "
  };}


查看完整回答
反对 回复 2019-08-19
?
ibeautiful

TA贡献1993条经验 获得超5个赞

只有一种情况,如果你需要进行AOT编译,你必须避免使用箭头功能,如此处所述

配置模块时,不能使用箭头功能。

❌DONT:

import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { Routes, RouterModule } from '@angular/router';@NgModule({
  imports: [
    BrowserModule,
    RouterModule,
    HttpModule,
    RouterModule.forRoot([], { errorHandler: (err) => console.error(err) })
  ],
  bootstrap: [
    AppComponent
  ],
  declarations: [
    AppComponent
  ]})export class AppModule {}

✅做:

import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { Routes, RouterModule } from '@angular/router';function errorHandler(err) {
  console.error(err);}@NgModule({
  imports: [
    BrowserModule,
    RouterModule,
    HttpModule,
    RouterModule.forRoot([], { errorHandler })
  ],
  bootstrap: [
    AppComponent
  ],
  declarations: [
    AppComponent
  ]})export class AppModule {}


查看完整回答
反对 回复 2019-08-19
  • 3 回答
  • 0 关注
  • 987 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信