2017-07-03 82 views
0

我有一個服務可以異步獲取一些數據。它導致組件渲染或我認爲。在承諾的解決方案中只有一個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!'); 
} 

錯誤:

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

帶你從無極的/可觀察的完成設置myViewProperty猜測...嘗試實現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 Angular2調用的生命週期鉤子表明Angular創建了組件。