Angular 2 ngOnInit未调用

Vin*_*Ken 28 typescript ngoninit angular

我正在构建一个版本为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');
  }
}
Run Code Online (Sandbox Code Playgroud)

应用程序的路由:

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

检查用户是否已登录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();
    }
  })
}
Run Code Online (Sandbox Code Playgroud)

浏览器是一个我存储浏览器特定代码的类.这是gotoMain函数:

gotoMain() {
  this._router.navigate([this._browser.main]);
}
Run Code Online (Sandbox Code Playgroud)

this._browser.main 在这种情况下,"概述"只是一个字符串.

Gün*_*uer 65

我想这是一个区域问题.

注入NgZone(从中导入)angular2/core

constructor(private zone:NgZone) {}

this._browser.getStorageValue('api_key', api_key => {
  if (api_key) {
    this.zone.run(() => this._browser.gotoMain());
  }
})
Run Code Online (Sandbox Code Playgroud)

  • Angular在修补区域中运行其代码,其中修补了`addEventListener()`,`setTimeout()`和其他异步API,以便在异步操作发生时重新运行更改检测时通知Angular.这使得变化检测非常有效.当调用代码以某种方式循环Angulars区域时,Angulars更改检测不会启动.如果从Angulars区域外调用的代码调用方法(甚至来自Angular组件或类似的方法),所有内容都在区域之外运行,直到此事件已完全处理.使用`zone.run(...)`强制执行返回Angulars区域. (12认同)