亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

我應該在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條經驗 獲得超6個贊

只有一種情況,如果你需要進行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 關注
  • 1103 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號