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/) –