简体   繁体   English

Ionic3事件无法正常工作

[英]Ionic3 Events not working

I am using events in my Ionic3 app. 我在Ionic3应用程序中使用事件

For eg I am using events to redirect the user to login screen whenever any API response gives HTTP 401. 例如,每当任何API响应给出HTTP 401时,我都使用事件将用户重定向到登录屏幕。

So in my app.component.ts file I am doing: 所以在我的app.component.ts文件中,我正在做:

import { Component, ViewChild } from '@angular/core';
import { StatusBar } from '@ionic-native/status-bar';
import { Events } from 'ionic-angular';
import { Network } from '@ionic-native/network';
import { Toast } from '../utilities/toast';
import { LocalStorage } from '../utilities/localstorage';
import { Platform, MenuController, Nav } from 'ionic-angular';

@Component({
  templateUrl: 'app.html'
})
export class MyApp {

  @ViewChild(Nav) nav: Nav;
  rootPage: any;
  pages: Array<{title: string, pageName: string}>;
  guardian: any;

  constructor(
    public platform: Platform,
    public menu: MenuController,
    public statusBar: StatusBar,
    public events: Events,
    public network: Network,
    public toast: Toast,
    public storage: LocalStorage)
  {
    console.log('before unauthorised'); //This line works when a 401 occurs
    events.subscribe('unauthorised', () => {
      console.log('user unauthorised take to login page'); //While this doesn't
      this.storage.clear();
      this.nav.setRoot('LoginPage');
    });
  }
}

And in my api services file I am publishing the event: 在我的api服务文件中,我正在发布事件:

import { Http } from '@angular/http';
import { Injectable } from '@angular/core';
import { Toast } from '../utilities/toast';
import { Events } from 'ionic-angular';
import { LocalStorage } from '../utilities/localstorage';

@Injectable()
export class ServiceProvider {
    constructor(public http: Http,
        private toast: Toast,
        public events: Events,
        private storage: LocalStorage) {

    }

    getErrorMessages(errors) {
        if (errors.status == 401) {  //<= unauthorised
            this.toast.present('You need to login first!');
            this.events.publish('unauthorised');
        }

        let error_messages = [];
        if (errors.status == 422) { //<= validation error
            let validation_messages = JSON.parse(errors.text())
            for (var key in validation_messages) {
                if (validation_messages.hasOwnProperty(key)) {
                    var messages = validation_messages[key];
                    error_messages.push(...messages);
                }
            }
        } else { //<= timeout or http code 500, 405 etc.
            error_messages.push('Technical error occured... please try again later.');
        }
        return error_messages;
    }

}

What could have been the problem? 可能是什么问题? The code looks correct as per the ionic documentation. 根据离子文档,该代码看起来正确。

EDIT I am adding the child service code. 编辑我正在添加子服务代码。 So basically the service provider is the parent class for all the api services. 因此,基本上,服务提供者是所有api服务的父类。 For eg the auth service class extends the service class above and has the following method for fetching auth user: 例如,auth服务类扩展了上面的服务类,并具有以下用于获取auth用户的方法:

getAuthUser() {
    console.log('will fetch auth');

    let headers = new Headers({
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'Authorization': 'Bearer ' + this.getAuthToken()
    });
    let options = new RequestOptions({ headers: headers });

    return new Promise((resolve, reject) => {
        this.http.get(this.getApiUrl() + '/me', options)
            .timeout(this.getTimeOut())
            .map(res => res.json())
            .subscribe(response => {
                resolve(response);
                this.events.publish('auth_user_fetched');
            }, errors => {
                reject(this.getErrorMessages(errors));
            });
    });
}

Not that I am not using try catch here. 并不是说我没有在这里使用try catch。

What is happening is that app.component.ts acts as a Parent and your provider as a child. 发生的事情是app.component.ts充当父级,而您的提供者则充当子级。 Therefore, the event cannot be published and subscribed. 因此,该事件无法发布和订阅。

In your code console.log('before unauthorised'); //This line works when a 401 occurs 在您的代码console.log('before unauthorised'); //This line works when a 401 occurs console.log('before unauthorised'); //This line works when a 401 occurs works because app.component.ts is a file that gets called everytime you do some activity. console.log('before unauthorised'); //This line works when a 401 occurs有效,因为app.component.ts是一个文件,每次执行某项活动时都会被调用。 And this console is written in the constructor(resulting in it called everytime). 这个控制台是用构造函数编写的(导致每次调用它)。

What you can do is instead of using event for unauthorized functionality. 您可以做的是代替使用事件来获得未经授权的功能。 Create a function in your provider itself that will do 在提供程序本身中创建一个可以执行的功能

unauthorized() {
      console.log('user unauthorised take to login page'); 
      this.storage.clear();
      this.nav.setRoot('LoginPage');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM