Ionic version: (check one with "x")
[ ] 1.x (For Ionic 1.x issues, please use https://github.com/ionic-team/ionic-v1)
[ ] 2.x
[x] 3.x
I'm submitting a ... (check one with "x")
[x] bug report
[ ] feature request
[ ] support request => Please do not submit support requests here, use one of these channels: https://forum.ionicframework.com/ or http://ionicworldwide.herokuapp.com/
Current behavior:
Cannot extend ionViewCanEnter for authentication.
Expected behavior:
It would be great to be able to extend ionViewCanEnter the way we do with CanActivate in Angular, it makes the code DRY instead of checking for authentication in every single page.
Is it possible to extend ionViewCanEnter like in this example ?
import 'rxjs/add/operator/take';
import 'rxjs/add/operator/map';
import { Injectable } from '@angular/core';
import { Store } from '@ngrx/store';
import { Observable } from 'rxjs/Observable';
import * as Auth from '../actions/auth';
import * as fromAuth from '../reducers';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private store: Store<fromAuth.State>) {}
canActivate(): Observable<boolean> {
return this.store.select(fromAuth.getLoggedIn).take(1).map(authed => {
if (!authed) {
this.store.dispatch(new Auth.LoginRedirect());
return false;
}
return true;
});
}
}
You can make a parent class, like below, and extend it in each component you need guarded. I'm afraid that is the DRYest way to do it with Ionic currently. Also, this repo is for bugs and feature requests, not support issues, so in the future, please ask on the forums. https://forum.ionicframework.com/
export class AuthGuard {
constructor(private store: Store<fromAuth.State>) {}
ionViewCanLoad(): Observable<boolean> {
return this.store.select(fromAuth.getLoggedIn).take(1).map(authed => {
if (!authed) {
this.store.dispatch(new Auth.LoginRedirect());
return false;
}
return true;
});
}
}
@Component(...)
export class YourPage extends AuthGuard {
constructor(...) {
super()
}
}
@wbhob This seems to be a nice solution, I will try that!
Closing as this seems to be more of a general question, which is better asked on the ionic forum. Please continue this discussion there.
ionViewCanEnter(): Promise<boolean> {
return this.store
.select(fromApp.isGameDataLoaded)
.filter(value => value === true)
.take(1)
.toPromise();
}
Thanks for the issue! This issue is being locked to prevent comments that are not relevant to the original issue. If this is still an issue with the latest version of Ionic, please create a new issue and ensure the template is fully filled out.
Most helpful comment
You can make a parent class, like below, and extend it in each component you need guarded. I'm afraid that is the DRYest way to do it with Ionic currently. Also, this repo is for bugs and feature requests, not support issues, so in the future, please ask on the forums. https://forum.ionicframework.com/