问题
I have a simple Ionic3 app with a couple of lazy loaded pages (using IonicPage) and a login page. I want to block all access to any page unless the user is first logged in. Knowing that this is to build a website version and not a cordova version, what is the best way to prevent the user for simply typing in the url of the lazy loaded pages and access them without logging in? I'm guessing there must be some way to "tap" into the navigation and redirect to the login page from there but cannot find this anywhere in the documentation. Obviously I don't want to add the same code in every lazy-loaded page to do this.
Here is my idea on how this would work, keeping the logic of things where it should be:
// app.component.ts
import { UserAuthService } from '..';
export class MyApp {
constructor(userAuth: UserAuthService) {
userAuth.init(<whatever dependency needed>);
userAuth.unauthorized().subscribe((auth: boolean) => {
if (auth) {
this.nav.setRoot(HomePage);
}
else {
this.nav.setRoot(LoginPage);
this.nav.popToRoot();
}
});
}
}
// user-auth.service.ts
export class UserAuthService {
private auth: ReplaySubject;
init(): {
// code here to catch whatever page change there is, check if user is authorized and push new value
}
unauthorized(): Observable<boolean> {
return this.auth.asObservable();
}
}
And bonus point if I can return to the origin page after logging in successfully
回答1:
After hours of working, finally i found a solution:
Step1: Defind a name for your ion-nav in app.html:
<ion-nav id="nav" #navCtrl [root]="rootPage"></ion-nav>
Step2: Get your nav by Viewchild in app.component.ts:
@ViewChild("navCtrl") nav: NavController;
Step3: Catch ionViewDidEnter of every page in app.component.ts:
ngAfterViewInit() {
this.nav.viewDidEnter.subscribe(event=>{
//If user is not logged in
if(!this.checkUserLoggedIn()){
if(event.name != "YourLoginPage")this.nav.setRoot("YourLoginPage");
}
})
}
checkUserLoggedIn(){
//Your code to check whether user is logged in or not
}
来源:https://stackoverflow.com/questions/46484512/ionic-require-login-on-lazy-loaded-page-for-website