Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

typescript - Angular 2 ngOnInit not called

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');
  }
}

The Routing of the app:

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

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?

Both the RegisterComponentand the LoginComponent use

ngOnInit() {
  this._browser.getStorageValue('api_key', api_key => {
    if (api_key) {
      this._browser.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 is just a string in this case 'Overview'.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I guess it's a zone issue.

Inject NgZone (import from angular2/core

constructor(private zone:NgZone) {}

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...