2016-08-26 7 views
0

以下の指令があります。ngOnInitプライベートメンバーの公開状況

ngOnInitからは、this.wordとthis.componentsの両方が「未定義」です。

誰でも私の理由を説明できますか?このことにより、重触発

import { Directive , Input, Output, ViewContainerRef, ComponentRef, DynamicComponentLoader, EventEmitter, OnInit, NgModule} from '@angular/core'; 
import { BrowserModule } from '@angular/platform-browser'; 
import { Widget } from '../widget.model'; 
import { CommentComponent } from './comment.component'; 


@Directive({selector: 'widget-factory'}) 
export class WidgetFactory { 
    @Input() name: any; 
    @Input() id: Number; 

    @Output() loaded = new EventEmitter(); 

    private components: { 'Comment': CommentComponent }; 
    private word: "hello"; 

    constructor(
    private _dcl: DynamicComponentLoader, 
    private _elementRef: ViewContainerRef 
) { 

    } 

    ngOnInit() { 
    // Get the current element 
    console.log(this.word); 
    let component: any; 
    //if(this[name] === 'Comment') { 
     component = CommentComponent 
    //} 
    this._dcl.loadNextToLocation(CommentComponent, this._elementRef); 
    console.log(this.name); 

    } 
} 

Outputting array of components in Angular 2

+0

'ngOnInit() '内に表示されないであろう' this.word'等という理由はありません。それらの「非公開」性質は、コードの動作に影響を与えないコンパイル時の概念にすぎません。私たちが見ていない何か他のものがなければならない。ちなみに、 'Comment'はどこに定義されていますか?あなたのコードが立っているので、これはコンパイルされないでしょう。とにかく実行すると、 'components'が初期化されたときに' ReferenceError'が得られます。 –

+0

コメントはどこに定義されていますか?おかげで、これは実際には間違いです。それはCommentComponentであり、CommentComponentはComponentです。それが私の問題を解決しました。 しかし、変数this.wordがクラス内に表示されません – Mikou

+0

コードを更新しました – Mikou

答えて

1
private word: "hello"; 

これは、そのタイプ "こんにちは" である "言葉" という名前のフィールドを定義します。私。それが持つことができる唯一の有効な値(undefinedとnullを除く)は "hello"です。フィールドを初期化しないので、まだ定義されていません。あなたは、文字列型のフィールドをしたい場合は、「こんにちは」、あなたは短い形式である

private word = "hello"; 

を必要とし、同じ説明がcomponentsの略

private word: string = "hello"; 

のため(おかげで推論を入力する)に初期化。

1

理由はかなり簡単です。typevalueの割り当てを混乱させただけです。

は今、あなたは持っている: private word: "hello";

する必要があります::はタイプ、=後のデフォルト値を行くprivate word: string = "hello";

後。

access_modificatior variable_name: type = default_value