[英]Ionic3 Events not working
我在Ionic3应用程序中使用事件 。
例如,每当任何API响应给出HTTP 401时,我都使用事件将用户重定向到登录屏幕。
所以在我的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');
});
}
}
在我的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;
}
}
可能是什么问题? 根据离子文档,该代码看起来正确。
编辑我正在添加子服务代码。 因此,基本上,服务提供者是所有api服务的父类。 例如,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));
});
});
}
并不是说我没有在这里使用try catch。
发生的事情是app.component.ts
充当父级,而您的提供者则充当子级。 因此,该事件无法发布和订阅。
在您的代码console.log('before unauthorised'); //This line works when a 401 occurs
console.log('before unauthorised'); //This line works when a 401 occurs
有效,因为app.component.ts
是一个文件,每次执行某项活动时都会被调用。 这个控制台是用构造函数编写的(导致每次调用它)。
您可以做的是代替使用事件来获得未经授权的功能。 在提供程序本身中创建一个可以执行的功能
unauthorized() {
console.log('user unauthorised take to login page');
this.storage.clear();
this.nav.setRoot('LoginPage');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.