angular: Angular2 router : Changing route doesn't load the component for first time
I am changing the route of angular2 application from ‘/’ to ‘/xyz’. For ‘xyz’ I have made a component named XYZComponent. This XYZComponent implements a hook for router lifecycle named “CanActivate”. In this hook I am changing the title of the page for new route. @CanActivate((next, prev) => { document.title = “mysite | xyz” return true; }) Then I implement OnInit for this component and call the method “ngOnInit()”. In this method I am calling the server to give me some data. This data is stored in a variable named xyzData, which is binded to the template. My template is:
<div class="xyzComp">
<p>{{xyzData.msg}}</p>
</div>
OnInit is:
ngOnInit(){
console.log("xyz component init");
this._myRestfulService.getXyz()
.subscribe(data => {
console.log("success",data);
this.xyzData = data;
}, err => {
this.xyzData = {msg:"cannot get data"};
console.log("error", err);
});
}
Changing the route is done by calling _route.navigate([“XYZ”]) from the click of a button named xyzBtn, which is present in the header of my app. The header is constant for all the routes. Problem is that when I click on xyzBtn for first time it calls only whatever written in @CanActivate decorator of XYZComponent. Next time when I click xyzBtn,@CanActivate is not called but this time ngOnInit() is called. Please help me on this. This problem occurs only when I deploy my code on server. The deployment server is NGINX server. On nginx server we have configured to ignore frontend routes. However my code works perfectly well on development server which is a npm module named lite-server.
About this issue
- Original URL
- State: closed
- Created 8 years ago
- Comments: 22 (7 by maintainers)
I had the same problem, and after ca. 4 hours investigation I’ve found that the problem was caused by systemjs/dist/system-polyfills.js. I removed this dependency and it works now at least in Chrome.
I need to add one more details: the component’s template was using
*ngIf
, so it was something related to change detection I assume.Here is a plunkr to reproduce: http://plnkr.co/edit/X8cXgf9GhfLZlVmo2fAK (you have to click the route link twice to get the component rendered) Just comment the
system-polyfills
inindex.html
to get it work… Works also if the*ngIf
is removed from the components.Plunker : https://plnkr.co/edit/E4HNXEjaIP7th77UE4dK?p=preview