2016-04-27 26 views
6

です:Angular2「これは」私はこのようなコード持っている未定義

export class CRListComponent extends ListComponent<CR> implements OnInit { 

    constructor(
     private router: Router, 
     private crService: CRService) { 
     super(); 
    } 

    ngOnInit():any { 
     this.getCount(new Object(), this.crService.getCount); 
    } 

ListComponentコードは、この

@Component({}) 
export abstract class ListComponent<T extends Listable> { 

    protected getCount(event: any, countFunction: Function){ 
     let filters = this.parseFilters(event.filters); 
     countFunction(filters) 
      .subscribe(
       count => { 
        this.totalItems = count; 
       }, 
       error => console.log(error) 
      ); 
    } 

され、CRServiceから適切なサービスコードフラグメントはこれです:

getCount(filters) { 
    var queryParams = JSON.stringify(
     { 
      c : 'true', 
      q : filters 
     } 
    ); 

    return this.createQuery(queryParams) 
     .map(res => res.json()) 
     .catch(this.handleError); 
} 

私のngOnInit()が実行されると、エラーが表示されます。

angular2.dev.js:23925 EXCEPTION: TypeError: Cannot read property 'createQuery' of undefined in [null]

ORIGINAL EXCEPTION: TypeError: Cannot read property 'createQuery' of undefined

したがって、基本的にreturn this.createQuery(queryParams)ステートメントのthisはnullになります。誰が考えているのですか?

+1

'this.createQuery'はなぜ存在すると思いますか? –

+2

あなたの2つのクラスが閉じ括弧を欠いているのは "普通"ですか? –

+0

私は不必要な部分を省略しました。そうでない場合、コードは構文的に正しいものです。 :)問題は '.createQuery'ではなく、' this'自体で問題になります。 – Sleeper9

答えて

7

問題は、次の場所にあります。

gOnInit():any { 
    this.getCount(new Object(), this.crService.getCount); // <---- 
} 

あなたは対象外機能を参照しているため。あなたはそれにbindメソッドを使用することもできます。

this.getCount(new Object(), this.crService.getCount.bind(this.crService)); 

または矢印機能にそれをラップ:

this.getCount(new Object(), (filters) => { 
    return this.crService.getCount(filters)); 
}); 

それは型を維持することができますので、第二のアプローチは、好ましいものであろう。詳細については、このページを参照してください:

+0

ありがとう、それは動作するようです! HTMLテンプレートのバインディングでこれを行う方法はありますか?つまり、私は次のコードを持っています: '(onLazyLoad)=" loadItems($ event、this.crService.getCRs) "' 私はこれを次のように変換できますか? (ページ、n、sortField、sortOrder、フィルタ)}) " – Sleeper9

+0

素晴らしいです!"#:。テンプレートで 'this'キーワードを使う必要はありません。つまり、私は中級レベルを使用します。私は 'loadItems'メソッド内でthis.crService.getCRsを使用しています... –

+1

良いですが、私もこの解決策に終わったのです。これは私のHTMLテンプレートにそのような醜いコードを埋め込むよりもはるかにクリーンなようです。助けてくれてありがとう! :) – Sleeper9

2

このエラーを修正するには、私は、エラーが離れていったエラーの原因となって、私の機能のうち、すべての内臓をヤンクし、別の関数にそれを投げました。例

this.globalListenFunc = renderer.listenGlobal('document', 'click', (event) => { 
    this.evaluateClick(event); 
}); 

evaluateClick(evt: MouseEvent){ 
    // all the code I yanked out from above 
} 
:私は、私は、コードを引っ張って

this.globalListenFunc = renderer.listenGlobal('document', 'click', (event) => { 
    // bunch of code to evaluate click event 
    // this is the code that had the "this" undefined error 
}); 

にいくつかのコードを使用してこの機能を有しており、外部のパブリック関数に入れて

は、ここに完成したコードです

関連する問題