2017-07-03 10 views
0

私はいくつかのデータを非同期的に取得するサービスを持っています。それはコンポーネントをレンダリングさせるか、または私が思うようにさせています。 promiseの解決にはconsole.logしかありません。レンダリングの原因は何ですか?コンポーネントの更新/レンダリングが発生しました

constructor(private viewService: viewService) { 
    console.log('[MyView component] construction started'); 

    viewService.getData(1).then(function(result) { 
     console.log('[MyView component] got data from service!'); 
    }); 

    console.log('[MyView component] construction complete!'); 
} 

エラー:あなたが約束の/観測の完了からmyViewPropertyを設定推測を取る

ERROR TypeError: Cannot read property 'myViewProperty' of undefined 
    at Object.eval [as updateDirectives] (MyViewComponent.html:23) 
    at Object.debugUpdateDirectives [as updateDirectives] (core.es5.js:12806) 
    at checkAndUpdateView (core.es5.js:12144) 
    at callViewAction (core.es5.js:12507) 
    at execComponentViewsAction (core.es5.js:12439) 
    at checkAndUpdateView (core.es5.js:12150) 
    at callViewAction (core.es5.js:12507) 
    at execEmbeddedViewsAction (core.es5.js:12465) 
    at checkAndUpdateView (core.es5.js:12145) 
    at callViewAction (core.es5.js:12507) 
+0

私は十分な情報ではないと確信しています。どこでエラーを引き起こす 'myViewProperty'を使用しますか? –

+0

何も設定されていません。それで、コンポーネントがどのようにリフレッシュするかわかりません。質問を変数 –

+0

で更新します。 'Promise'や' Observable'のイベントが完了すると、変更検出が実行され、再レンダリングが行われます。私はあなたが応答が到着する前でさえエラーを得ると思います。 –

答えて

0

... On Initを実装し、そうすることを試してみてください。

import { OnInit } from '@angular/core'; 
export class EventSelectionSearchComponent implements OnInit, OnDestroy { 


    constructor(private viewService: viewService) { 
    } 

    ngOnInit(): void { 
     this.viewService.getData(1) 
     .then(data => { 
      this.myViewProperty = data; 
     }); 
    } 

    [ ... ] 

} 

コンポーネントの入力、出力、または引数は、コンストラクタの呼び出しの後で利用できない場合があります。一方、ngOnInit Angularがコンポーネントの作成を完了したことを示すために、Angular2によって呼び出されるライフサイクルフック。

関連する問題