本文介绍了Angular 2 ngOnInit未调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am building an Angular 2 app with version beta.8.
In this app i have a component which implements OnInit.
In this component i have the function ngOnInit, but the ngOnInit function is never called.

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']).
重定向到Overview.如果我默认使用概述"路由,则可以在控制台中看到ngOnInit.
因此,我重定向页面的方式似乎是问题所在.
如何重定向到概述"页面并调用ngOnInit函数?

There is a check to see if the user is already logged in inside the LoginComponent and RegisterComponent.
If the user is logged in, the components redirect to Overview using: router.navigate(['Overview']).
If i use the Overview route as default i do see ngOnInit inside the console.
So the way i redirect my page seems to be the problem.
How can redirect to the Overview page and call the ngOnInit function?

RegisterComponentLoginComponent都使用

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

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

Browser is a class in which i store browser specific code.This is the gotoMain function:

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

在这种情况下,

this._browser.main只是一个字符串.

this._browser.main is just a string in this case 'Overview'.

推荐答案

我认为这是区域问题.

注入NgZone(从angular2/core

constructor(private zone:NgZone) {}

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

这篇关于Angular 2 ngOnInit未调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 15:09