简体   繁体   English

Angular2路由器和OnInit

[英]Angular2 Router and OnInit

I recently started having difficulty with the Angular2 router. 我最近开始在Angular2路由器上遇到困难。 The issue was that components that were outside the router-outlet would have their ngOnInit methods called. 问题是router-outlet之外的组件将调用其ngOnInit方法。 But components that were inside the router-outlet would not. 但是router-outlet内的组件则不会。

I'd had previous issues with the Angular2 router as well . 我以前也曾在Angular2路由器上遇到过问题 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. 但是这个问题似乎与外部Javascript代码有关,而这个问题显然与Angular2生命周期挂钩有关。

I put together some Plunker's but couldn't reproduce the issues. 我整理了一些Plunker,但无法重现这些问题。 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. 因此,我将其发布为问题,并附上我所找到的答案,以防其他人遇到此问题。

As I mentioned before, I'd see other issues with the Angular2 router. 如前所述,我会看到Angular2路由器的其他问题。 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. 我在这里略微扭转了这种趋势,并且没有使用SystemJS。 Instead, I'm just doing a simple webpack build. 相反,我只是在做一个简单的webpack构建。 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. 我还看到了其他一些问题和stackoverflow问题,其中提到了script标记顺序的重要性。 Well, since webpack takes direct control of such things away from me, I didn't really pay attention. 嗯,由于webpack可以直接控制这些事情,所以我并没有真正注意。 But it turns out it is important. 但是事实证明这很重要。

I'm currently producing a bundle.js file from webpack . 我目前正在从webpack生成bundle.js文件。 But what I didn't appreciate is that you also have to find a way to include the angular2-polyfills.js in your application. 但是我不感激的是,您还必须找到一种在应用程序中包含angular2-polyfills.js方法。 I kind of assumed it would somehow get included by webpack somehow, but it doesn't. 我有点假设它将以某种方式包含在webpack ,但事实并非如此。

The first thing I tried was to simply add it into the <head> section of my index.html. 我尝试做的第一件事就是将其简单地添加到index.html的<head>部分中。 This loads it outside of webpack , and that seems to be sufficient. 这会将其加载到webpack之外,这似乎已经足够。 I also found that I could just include by adding: 我还发现我可以添加以下内容:

require('angular2/bundles/angular2-polyfills');

...in my webpack entrypoint. ...在我的webpack入口点。

Once the angular2-polyfills.js file was in place, the lifecycle hooks were getting properly called. angular2-polyfills.js文件后,即可正确调用生命周期挂钩。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM