Reputation: 35
I am using ionic2 in a new application , and i want to route my page inside a promise function that calls a http request from a server,
I want to access the Navcontroller inside a promise function , but the Navcontroller is not accessible from inside the promise function.
the promise function is a promise of a function inside the AuthenticationService
this is my code inside app.component.ts :
import {Component, ViewChild, Inject} from '@angular/core';
import {Platform, NavController} from 'ionic-angular';
import { StatusBar } from 'ionic-native';
import { HomePage } from '../pages/home/home';
import { LoginPage } from '../pages/login/login';
import {Authentication} from '../providers/authentication';
@Component({
template: `<ion-nav #myNav [root]="rootPage"></ion-nav>`,
providers:[Authentication],
})
export class MyApp {
@ViewChild('myNav') public nav : NavController
//rootPage = LoginPage;
constructor(platform: Platform, private auth:Authentication) {
platform.ready().then(() => {
StatusBar.styleDefault();
});
}
ngOnInit() {
this.auth.index()
.then(function (data) {
if(data['flag']==1)
{
this.nav.setRoot(HomePage);
}
else
{
this.nav.setRoot(LoginPage);
}
})
and this is the error :
EXCEPTION: Uncaught (in promise): TypeError: Cannot read property 'nav' of null
TypeError: Cannot read property 'nav' of null.
Upvotes: 2
Views: 574
Reputation: 40647
Change
.then(function (data) {
to
.then( (data) => {
If you use function
instead of the fat arrow syntax, your this
won't be refering to the page.
I'd recommend you to read: https://stackoverflow.com/a/20279485/5706293
Upvotes: 2