首页 文章

Angular 2 ngOnInit未调用

提问于
浏览
22

我正在构建一个版本为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 .
如果用户已登录,则组件将使用以下内容重定向到Overview: router.navigate(['Overview']) .
如果我使用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 在这种情况下只是一个字符串'Overview' .

2 回答

  • 53

    我想这是一个区域问题 .

    注入 NgZone (从 angular2/core 导入

    constructor(private zone:NgZone) {}
    
    this._browser.getStorageValue('api_key', api_key => {
      if (api_key) {
        this.zone.run(() => this._browser.gotoMain());
      }
    })
    
  • 0

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

相关问题