组件更新/渲染被触发
问题描述:
我有一个服务可以异步获取一些数据。它导致组件渲染或我认为。在承诺的解决方案中只有一个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)
答
带你从无极的/可观察的完成设置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创建了组件。
我很确定这不是足够的信息。你在哪里使用'myViewProperty'导致错误? –
事情是没有什么被设置的。然后我看不出它是如何导致组件刷新。我将使用变量更新问题 –
“Promise”或“Observable”事件的完成会导致更改检测运行,从而导致重新呈现。我猜你甚至在响应到达之前就会得到错误。 –