In my Ionic3 app, I utilize events for various functionalities.
For example, I employ events to automatically redirect the user to the login screen whenever an API response returns HTTP 401.
Thus, within my app.component.ts
file, I have the following setup:
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');
});
}
}
Furthermore, in my API services file, I trigger the event as follows:
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;
}
}
Despite following the Ionic documentation, there seems to be an issue. What could possibly be causing it?
EDIT Adding the child service code: The service provider serves as the parent class for all API services. For instance, the authentication service class extends the aforementioned service class and includes a method for retrieving the authenticated user:
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));
});
});
}
It's worth noting that no try-catch statements are used here.