离子需要登录网站的延迟加载页面 [英] ionic require login on lazy loaded page for website

查看:109
本文介绍了离子需要登录网站的延迟加载页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的Ionic3应用程序,带有几个延迟加载的页面(使用 IonicPage )和一个登录页面。我希望阻止对任何页面的所有访问,除非用户首次登录。知道这是建立网站版本而不是cordova版本,防止用户只是输入懒惰网址的最佳方法是什么加载页面并访问它们而无需登录?我猜测必须有一些方法可以点击导航并从那里重定向到登录页面,但在文档中的任何地方都找不到。显然我不想在每个延迟加载的页面中添加相同的代码来执行此操作。

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步:在app.html中为 ion-nav 定义名称:

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>

第2步:获取 nav by Viewchild in app.component.ts

Step2: Get your nav by Viewchild in app.component.ts:

@ViewChild("navCtrl") nav: NavController;

Step3: Catch ionViewDidEnter 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
}

这篇关于离子需要登录网站的延迟加载页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆