Controlling Nav (accessing Pages) from an Injectable service


#1

I have an injectable service (OAuth2 client) and I want to log the user out and redirect them to a LoginPage when their access token is expired and refresh token is invalid/fails (see previous topic on handling refresh tokens here: oauth2 API calls and refreshing tokens (chaining observables?) )

I tried using IonicApp and app.getComponent(‘root-nav’) to get my NavController, and that seemed to work fine, until I tried to call setRoot(LoginPage). Then it barfs and asks for LoginPage to be injectable.

import {IonicApp, NavController, Storage, SqlStorage} from 'ionic-framework';
import {LoginPage} from '../pages/login/login';

@Injectable()
export class WAC {
    constructor(http:Http, app:IonicApp) {
        this.http = http;        
        this.app = app;
    }
	
    logout() {
        this.storage.remove('oauth');
        let nav = this.app.getComponent('root-nav');
        this.nav.setRoot(LoginPage);
    }
}

Thanks!


#2

Same problem here:

app.bundle.js:34352 EXCEPTION: Cannot resolve all parameters for 'LoginPage'(undefined, NavController). Make sure that all the parameters are decorated with Inject or have valid type annotations and that 'LoginPage' is decorated with Injectable.

The first param is my custom service which I’ve already registered as a provider in the @App decorator.


#3

The app design is your problem. Service does not work with views, the controller should work with them. You must fix your architecture design.


#4

Do you have a recommendation? If I have dozens of pages making API calls via the service and I’d like them all to handle invalid tokens the same, is what’s the best way to do that without handling the error and forwarding to logout on each and every API call response if not in the API class itself?

Thanks,
Brian


#5

On good, API service returns an error to the controller, which it has caused. And this controller redirects to login page. But I understand you… So you could pass NavController to your API service from the controller.

Something like:

this._apiService.getUser(this.nav)

public getUser(nav: NavController) { nav.setRoot(LoginPage) }


#6

I got around this by publishing an event and subscribing to it in the @app component.


#7

Hi JaiKrish,

Do you mind posting some sample code for subscribing and publishing model?


#8

You should publish a custom event from the Injectible service and subscribe to it in the app.ts
Refer:http://ionicframework.com/docs/v2/api/util/Events/