ionic2 初步实现 Authentication

本文介绍了一个基于Ionic框架的应用如何实现用户登录状态管理。通过使用BehaviorSubject来跟踪用户的登录状态,并据此更新应用的主页,确保只有认证用户才能访问特定内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

用处:当用户打开 APP 后会判断用户 token 是否已失效,若未失效则进入首页,否则进入登录页面。当用户登出或正在操作的时候 token 失效都会回到登录界面。

首先我们新建一个 provider:ionic g provider AuthenticationService

打开这个文件,引用BehaviorSubject:import { BehaviorSubject } from 'rxjs/BehaviorSubject';

BehaviorSubject 是 Subject 的一个衍生类,具有“最新的值”的概念。它总是保存最近向数据消费者发送的值,当一个 Observer 订阅后,它会即刻从 BehaviorSubject 收到“最新的值”。

代码如下:

export class AuthenticationService {

  activeUser = new BehaviorSubject(null);

  constructor() {
  }

  doLogin(_username) {
    this.activeUser.next(_username);
  }

  doLogout() {
    this.activeUser.next(null);
  }

}

接下来我们来注册用户认证事件。

打开 app.component.ts 文件,引入 AuthenticationService,注册用户认证事件以及 rootPage,代码如下:

export class MyApp {
  rootPage: any;
  public static backButtonPressed: boolean = false; // 用于判断返回键是否触发
  @ViewChild('myNav') nav: Nav;

  constructor(public ionicApp: IonicApp, public platform: Platform, 
    private toastService: ToastService, private paramService: ParamService, 
    private auth: AuthenticationService) {
    platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      StatusBar.styleDefault();
      Splashscreen.hide();

      if (!this.paramService.isNull(localStorage.getItem("token_name"))) {
        auth.doLogin(localStorage.getItem("token_name"));
      }

      this.registerBackButtonAction(); // 注册返回按键事件
      this.registerAuthentication(); // 注册用户认证事件
    });
  }

  registerAuthentication() {
    this.auth.activeUser.subscribe((_user) => {
      if (_user) {
        this.rootPage = TabsPage;
      } else {
        this.rootPage = LoginPage;
      }
    });
  }

  registerBackButtonAction() {
    this.platform.registerBackButtonAction(() => {
      this.backButtonAction();
    }, 999);
  }

  backButtonAction() {
    // 如果想点击返回按钮隐藏 toast 或 loading 或 Overlay 就把下面加上
    // this.ionicApp._toastPortal.getActive() || this.ionicApp._loadingPortal.getActive() || this.ionicApp._overlayPortal.getActive()
    let activePortal = this.ionicApp._modalPortal.getActive();
    if (activePortal) {
      activePortal.dismiss().catch(() => {});
      activePortal.onDidDismiss(() => {});
      return;
    }

    let activeVC = this.nav.getActive();
    let page = activeVC.instance;

    if (!(page instanceof TabsPage)) {
      if (!this.nav.canGoBack()) {
        return this.showExit();
      }
      return this.nav.pop();
    }

    let tabs = page.tabs;
    let activeNav = tabs.getSelected();
    return activeNav.canGoBack() ? activeNav.pop() : this.showExit();
  }

  showExit() {
    if (MyApp.backButtonPressed) {
      this.platform.exitApp();
    }

    MyApp.backButtonPressed = true;
    this.toastService.presentToast("再点一次退出");
    setTimeout(() => {
      MyApp.backButtonPressed = false;
    }, 2000);
  }
}

首先对 localStorage 中检验是否有保留用户登录信息,若有则初始化用户认证并进入首页,否则进入登录页。

接下来就是业务中对 AuthenticationService 的操作,分别调用 doLogin 和 doLogout 来实现用户登录和登出。

当 activeUser 发生改变时就会触发订阅时的回调函数,判断用户状态来操作 rootPage 实现登录登出功能。


以后将进一步实现 Authentication 的功能。


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值