Angular 2 ngOnInit未调用

时间:2016-03-11 09:32:58

标签: angular typescript ngoninit

我正在构建一个版本为beta.8的Angular 2应用程序 在这个应用程序中,我有一个实现OnInit的组件 在这个组件中,我有函数ngOnInit,但从不调用ngOnInit函数。

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

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

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

应用的路由:

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

检查用户是否已登录LoginComponent和RegisterComponent 如果用户已登录,则组件将使用以下内容重定向到“概览”:router.navigate(['Overview']) 如果我使用概览路线作为默认路线,我会在控制台内看到ngOnInit 所以我重定向我的页面的方式似乎是问题 如何重定向到Overview页面并调用ngOnInit函数?

RegisterComponentLoginComponent都使用

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

浏览器是一个用于存储特定于浏览器的代码的类。 这是gotoMain函数:

gotoMain() {
  this._router.navigate([this._browser.main]);
}
在这种情况下,

this._browser.main只是一个字符串'概述'。

2 个答案:

答案 0 :(得分:57)

我想这是一个区域问题。

注入NgZone(从angular2/core

导入
constructor(private zone:NgZone) {}

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

答案 1 :(得分:-1)

生命周期钩子(如OnInit())使用指令和组件。它们不能与其他类型一起使用,例如服务。查看此link了解更多