简体   繁体   English

Angular 2 ngOnInit未调用

[英]Angular 2 ngOnInit not called

I am building an Angular 2 app with version beta.8. 我正在构建一个版本为beta.8的Angular 2应用程序。
In this app i have a component which implements OnInit. 在这个应用程序中,我有一个实现OnInit的组件。
In this component i have the function ngOnInit, but the ngOnInit function is never called. 在这个组件中我有函数ngOnInit,但从不调用ngOnInit函数。

import { Component, OnInit } from 'angular2/core';

@Component({
  templateUrl: '/app/html/overview.html'
})

export class OverviewComponent implements OnInit {
  ngOnInit() {
    console.log('ngOnInit');
  }
}

The Routing of the app: 应用程序的路由:

@RouteConfig([
  {
    path: '/overview',
    name: 'Overview',
    component: OverviewComponent
  },
  {
    path: '/login',
    name: 'Login',
    component: LoginComponent
  },
  {
    path: '/register',
    name: 'Register',
    component: RegisterComponent,
    useAsDefault: true
  }
])

There is a check to see if the user is already logged in inside the LoginComponent and RegisterComponent. 检查用户是否已登录LoginComponent和RegisterComponent。
If the user is logged in, the components redirect to Overview using: router.navigate(['Overview']) . 如果用户已登录,则组件将重定向到Overview: router.navigate(['Overview'])
If i use the Overview route as default i do see ngOnInit inside the console. 如果我使用Overview路由作为默认路由,我会在控制台中看到ngOnInit。
So the way i redirect my page seems to be the problem. 所以我重定向我的页面的方式似乎是问题。
How can redirect to the Overview page and call the ngOnInit function? 如何重定向到Overview页面并调用ngOnInit函数?

Both the RegisterComponent and the LoginComponent use RegisterComponentLoginComponent使用

ngOnInit() {
  this._browser.getStorageValue('api_key', api_key => {
    if (api_key) {
      this._browser.gotoMain();
    }
  })
}

Browser is a class in which i store browser specific code. 浏览器是一个我存储浏览器特定代码的类。 This is the gotoMain function: 这是gotoMain函数:

gotoMain() {
  this._router.navigate([this._browser.main]);
}

this._browser.main is just a string in this case 'Overview'. this._browser.main在这种情况下只是一个字符串'Overview'。

I guess it's a zone issue. 我想这是一个区域问题。

Inject NgZone (import from angular2/core 注入NgZone (从angular2/core导入

constructor(private zone:NgZone) {}

this._browser.getStorageValue('api_key', api_key => {
  if (api_key) {
    this.zone.run(() => this._browser.gotoMain());
  }
})

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

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