在离子2中的Promist函数内部的NAV



我在新应用程序中使用了ionic2,我想将页面路由我的页面中,该页面从服务器调用http请求,

我想在Promise功能中访问NavController,但是从Promise功能内部无法访问NavController。承诺功能是Authenticationservice内部功能的承诺
这是我的代码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);
                    }
                })

这是错误:

EXCEPTION: Uncaught (in promise): TypeError: Cannot read property 'nav' of null    
TypeError: Cannot read property 'nav' of null.

更改

.then(function (data) {

to

.then( (data) => {

如果您使用function代替脂肪箭头语法,则this不会参考页面。

我建议您阅读:https://stackoverflow.com/a/20279485/5706293

最新更新