我應(yīng)該在Angular的類中編寫方法作為箭頭函數(shù)在Angular中,在技術(shù)上可以將類方法編寫為ES2015箭頭函數(shù),但我從未真正見過有人這樣做過。以這個簡單的組件為例:@Component({
selector: 'sample'})export class SampleComponent {
arrowFunction = param => {
// Do something
};
normalFunction(param) {
// Do something
}}這沒有任何問題。有什么不同嗎?為什么我應(yīng)該或不應(yīng)該使用它?
3 回答

BIG陽
TA貢獻(xiàn)1859條經(jīng)驗 獲得超6個贊
類箭頭函數(shù)的一個很好的用例是當(dāng)你想將一個函數(shù)傳遞給另一個組件并在函數(shù)中保存當(dāng)前組件的上下文時。
@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
能夠調(diào)用父組件的函數(shù)并且文本將被正確地更新,就好像我只是將父級更改為:
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 " };}

ibeautiful
TA貢獻(xiàn)1993條經(jīng)驗 獲得超6個贊
只有一種情況,如果你需要進(jìn)行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 {}
- 3 回答
- 0 關(guān)注
- 1100 瀏覽
添加回答
舉報
0/150
提交
取消