簡體   English   中英

打字稿/ Angular 2問題

[英]Typescript/Angular 2 issue

我是新手,甚至不確定我的問題是Typescript還是Angular2的誤解...

我有以下代碼(減少到最少):

import {OnInit, Component} from 'angular2/core';
import {bootstrap} from 'angular2/platform/browser';

@Component({
    selector: 'hello-app',
    template: `
        <h1>Foo:{{foo}}</h1>
    `
})
export class HelloApp implements OnInit {
    foo:  string;

    ngOnInit() {
      this.loadFoo();
    }

    loadFoo()
    {
      this.loadInput(function(input: string) {
        this.foo = input;
      })
    }

    ​loadInput (callback) {
        callback ("bar");
    }
}

bootstrap(HelloApp);

轉錄並在瀏覽器中運行后,我在瀏覽器調試器中收到以下錯誤消息:

angular2.min.js:17 TypeError: Cannot set property 'foo' of undefined
    at hello.js:34
    at HelloApp.loadInput (hello.js:38)
    at HelloApp.loadFoo (hello.js:31)
    at HelloApp.ngOnInit (hello.js:28)
    at e.ChangeDetector_HostHelloApp_0.detectChangesInRecordsInternal (viewFactory_HostHelloApp:21)
    at e.detectChangesInRecords (angular2.min.js:6)
    at e.runDetectChanges (angular2.min.js:6)
    at e.detectChanges (angular2.min.js:6)
    at t.detectChanges (angular2.min.js:4)
    at angular2.min.js:9

誰知道為什么這里沒有定義“ this”,使用回調方法設置{{foo}}中的內容的選項是什么?

謝謝 !

您需要使用箭頭功能,以便可以使用詞法this關鍵字:

this.loadInput((input: string) => {
    this.foo = input;
  });

請參閱此鏈接,以獲取有關箭頭功能詞匯this的更多提示:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM