javascript - ionic 2 中 Promise 函数内的 nav

标签 javascript angular typescript ionic2

我在一个新应用程序中使用 ionic2,并且我想将我的页面路由到一个从服务器调用 http 请求的 Promise 函数内,

我想访问 Promise 函数内的 Navcontroller,但无法从 Promise 函数内部访问 Navcontroller。 Promise 函数是 AuthenticationService 内部函数的 Promise
这是我在 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) {

.then( (data) => {

如果您使用 function 而不是粗箭头语法,您的 this 将不会引用该页面。

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

关于javascript - ionic 2 中 Promise 函数内的 nav,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41400671/

相关文章:

javascript - 在函数签名中使用 TypeScript 类型的对象值

angular - Javascript removeEventListener OnDestroy 在 Angular 6 中不起作用

javascript - Reactjs 处理元素的滚动以查看其是否可见

css - Angular6:如何为复选框添加边框颜色

javascript - Javascript 上的正则表达式

angular - 源映射在 Angular2 的单元测试中不起作用

angular - 使用 setter 方法 ["set()"] 在 HttpParams 下

typescript - Svelte/SvelteKit 和 Typescript : add properties to the window object, 或扩展接口(interface)

javascript - 回调/Promise 嵌套循环,2 个 API 调用

javascript - 类型错误 : Cannot read property 'upvote' of undefined in mean stack