1

鑑於此代碼:角2路由訂製改變檢測

ngOnInit() { 
    this.apiService.getBlogPosts().subscribe(blogPosts => { 
     this.allBlogPosts = blogPosts; 

     this.changeDetector.detectChanges(); 
    })); 
} 

我試圖理解爲什麼我不得不使用this.changeDetector.detectChanges();

的情況是,如果我打開我的博客路線的第一次,我的帖子加載罰款,如果我route到另一個頁面(或者其他component或相同的「博客」 component顯示某個帖子的細節(如「博客/我-後」)),那麼我route回「博客「組件('blog /'),這次模板無法更新與職位。我可以在我的InspectNetwork標籤看到,該路由得到的職位仍在工作,console.log是表示一切似乎順利通了,但模板沒有更新,除非我強迫變化檢測。這是預期的行爲?可以補救嗎?這似乎很奇怪...

另一個值得注意的事情是,無論是第一次和3時,我參觀「博客」 component我用:

this.router.navigate([`/${url}`]); 

來找到它......而這沒法子......

編輯:getBlogPosts()方法是我ApiService,我注入我的BlogComponent

public getBlogPosts() : Observable<BlogPost[]> { 
    return this.http.get(`${ environment.apiUrl }GetBlogPosts`, { headers: this.headers }) 
        .map((response: Response) => <BlogPost[]>response.json()); 
} 
+0

是什麼'this.apiService.getBlogPosts() '?顯示代碼 –

+0

當然,看看編輯。你的時間非常感謝。 –

+0

_I返回到「博客」組件 - 你怎麼做? –

回答

1

角度使用NgZone在應該運行更改檢測週期時收到通知。 NgZone使用zone.js截獲像setTimeoutnew PromiseXHR請求等所有異步操作所以平時它的工作原理,而不從開發任何額外的努力,在引擎蓋下。

然而,觸發如果你不是由zone.js逮住你不會變化檢測一些操作,並有做手工。但是您可以使用NgZone在Angular區域中執行某些操作,這意味着在回調完成執行後,Angular將運行更改檢測。

所以你的情況,你可以嘗試這樣的事:

this.routerSubject.subscribe((url: string) => { NgZone.run(() => this.router.navigate([/${url}]); }); 

其中NgZone可注入任何角度組件或服務:

constructor(zone: NgZone) {} 
+0

你太棒了,謝謝! –

+1

@SerjSagan,不客氣)關注[我在中](https://blog.angularindepth.com/) –