[英]Is it safe to use setTimeout in production code?
我有一個使用Material Design Lite的angular2組件,但是復選框(可能還有其他)的元素在組件的第一次加載時未正確呈現,而如果我與復選框交互,則將正確應用mdl樣式。 在我的組件中
ngAfterViewInit() {
componentHandler.upgradeDom();
}
但這不能解決我的問題,因此我在服務返回一些數據后立即使用了setTimeout。 這似乎可行,但建議這樣做嗎?
this.service.getDetails(this.id)
.finally(() => {
setTimeout(() => {
componentHandler.upgradeDom();
}, 10);
})
.subscribe((details) => {
this.details = details;
});
如果您也將組件設置添加到問題中,將會有所幫助。 看一下angular.io文檔的Component Styles部分。 我想您所需要的就是將選擇器和樣式添加到組件的注釋中。 從文檔:
@Component({
selector: 'hero-app',
template: `
<h1>Tour of Heroes</h1>
<hero-app-main [hero]=hero></hero-app-main>`,
styles: ['h1 { font-weight: normal; }']
})
export class HeroAppComponent {
/* . . . */
}
完全不了解您代碼的來龍去脈,純粹是從理論上講,您引入了一種競爭條件,其中(造成延遲的原因)必須在10ms內完成。
您可以確認它將始終如此嗎? 如果可以(以100%的確定性),我會說很好。 但是,根據經驗,我會盡量避免超時,而盡可能使用事件。
請注意:我尚未使用Angular 2,但我知道在Angular 1中,摘要有時需要手動觸發。 這可能就是這里發生的事情。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.