代码之家  ›  专栏  ›  技术社区  ›  Vincent Kenbeek

未调用Angular 2 ngOnInit

  •  36
  • Vincent Kenbeek  · 技术社区  · 10 年前

    我正在构建一个版本为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']) .
    如果我默认使用Overview路由,我确实会在控制台中看到ngOnInit。
    所以我重定向页面的方式似乎是问题所在。
    如何重定向到概览页面并调用ngOnInit函数?

    两个 RegisterComponent LoginComponent 使用

    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 在本例中,“概述”只是一个字符串。

    1 回复  |  直到 9 年前
        1
  •  75
  •   Günter Zöchbauer    10 年前

    我想这是一个区域问题。

    注射 NgZone (从导入 angular2/core

    constructor(private zone:NgZone) {}
    
    this._browser.getStorageValue('api_key', api_key => {
      if (api_key) {
        this.zone.run(() => this._browser.gotoMain());
      }
    })
    
    推荐文章