问题
I recently started having difficulty with the Angular2 router. The issue was that components that were outside the router-outlet
would have their ngOnInit
methods called. But components that were inside the router-outlet
would not.
I'd had previous issues with the Angular2 router as well. But that issue seemed to be related to external Javascript code whereas this one seemed to be clearly an issue with the Angular2 lifecycle hooks.
I put together some Plunker's but couldn't reproduce the issues. So that is the problem. It turns out, I figured out what the issue was (and it was hinted at in some other things I'd read). So I'm posting this as a question and I'll include what I found as an answer in case anybody else runs into this issue.
回答1:
As I mentioned before, I'd see other issues with the Angular2 router. Now that I've dug into this more, I think they are related.
I'm bucking the trend here a little and not using SystemJS. Instead, I'm just doing a simple webpack build. That seems to be where the issue lies. I'd seen a few other issues and stackoverflow questions where they mentioned the importance of the order of script
tags. Well, since webpack
takes direct control of such things away from me, I didn't really pay attention. But it turns out it is important.
I'm currently producing a bundle.js
file from webpack
. But what I didn't appreciate is that you also have to find a way to include the angular2-polyfills.js
in your application. I kind of assumed it would somehow get included by webpack
somehow, but it doesn't.
The first thing I tried was to simply add it into the <head>
section of my index.html. This loads it outside of webpack
, and that seems to be sufficient. I also found that I could just include by adding:
require('angular2/bundles/angular2-polyfills');
...in my webpack entrypoint.
Once the angular2-polyfills.js file was in place, the lifecycle hooks were getting properly called.
来源:https://stackoverflow.com/questions/36338606/angular2-router-and-oninit