前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >ionic4初级教程-含登录、访问权限验证功能

ionic4初级教程-含登录、访问权限验证功能

作者头像
lilugirl
发布2019-05-28 17:56:08
2.5K0
发布2019-05-28 17:56:08
举报
文章被收录于专栏:前端导学前端导学
代码语言:javascript
复制
npm install -g ionic

ionic start ionic4_demo blank --type=angular

如果第一次安装的时候失败,没关系 删掉已经生成的ioinc4Learn文件包,重新运行命令

代码语言:javascript
复制
cd ionic4_demo
npm install --save @ionic/storage

创建新页面

代码语言:javascript
复制
ionic g page public/login
代码语言:javascript
复制
ionic g page public/register
代码语言:javascript
复制
ionic g page members/dashboard
代码语言:javascript
复制
ionic g service services/authentication 
代码语言:javascript
复制
ionic g service services/authGuard
代码语言:javascript
复制
ng generate module members/member-routing --flat

启动项目

代码语言:javascript
复制
ng serve

给app.module.ts添加IonicStorageModule

删除src/app/home文件夹 ,调整app-routing.module.ts的首页路由配置

设置authentication.service.ts文件

代码语言:javascript
复制
import { Platform } from '@ionic/angular';
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
import { Storage } from '@ionic/storage';

const TOKEN_KEY = 'auth-token';

@Injectable({
  providedIn: 'root'
})
export class AuthenticationService {

  authenticationState = new BehaviorSubject(false);

  constructor(private storage: Storage, private plt: Platform) {
    this.plt.ready().then(() => {
      this.checkToken();
    });
  }

  login() {
    return this.storage.set(TOKEN_KEY, 'liuyi 123456').then(
      res => {
        this.authenticationState.next(true);
      }
    );
  }

  logout() {
    return this.storage.remove(TOKEN_KEY).then(() => {
      this.authenticationState.next(false);
    });
  }

  isAuthenticated() {
    return this.authenticationState.value;
  }

  checkToken() {
    return this.storage.get(TOKEN_KEY).then(res => {
      if (res) {
        this.authenticationState.next(true);
      }
    });
  }
}

设置 auth-guard.service.ts文件

代码语言:javascript
复制
import { Injectable } from '@angular/core';
import { CanActivate } from '@angular/router';
import { AuthenticationService } from './authentication.service';

@Injectable({
  providedIn: 'root'
})
export class AuthGuardService implements CanActivate {

  constructor(private authService: AuthenticationService) { }

  canActivate(): boolean {
    return this.authService.isAuthenticated();
  }
}

设置子路由member-routing.module.ts

代码语言:javascript
复制
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

const routes: Routes = [
  { path: 'dashboard', loadChildren: './dashboard/dashboard.module#DashboardPageModule' }
];

@NgModule({
  imports: [
    RouterModule.forChild(routes)
  ],
  exports: [RouterModule]
})
export class MemberRoutingModule { }

设置主路由app-routing.module.ts

代码语言:javascript
复制
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AuthGuardService } from './services/auth-guard.service';

const routes: Routes = [
  { path: '', redirectTo: 'login', pathMatch: 'full' },
  { path: 'login', loadChildren: './public/login/login.module#LoginPageModule' },
  { path: 'register', loadChildren: './public/register/register.module#RegisterPageModule' },
  {
    path: 'members',
    canActivate: [AuthGuardService],
    loadChildren: './members/member-routing.module#MemberRoutingModule'
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

对app.component.ts配置

然后对login resgister和 dashboard页面分别设置

其中login.page.html

代码语言:javascript
复制
<ion-header>
  <ion-toolbar>
    <ion-title>Login</ion-title>
  </ion-toolbar>
</ion-header>

<ion-content padding>
  <ion-button (click)="login()" expand="block">Login</ion-button>
  <ion-button expand="block" color="secondary" herf="/register" routerDirection="forward">Register</ion-button>
</ion-content>

login.page.ts

代码语言:javascript
复制
import { Component, OnInit } from '@angular/core';
import { AuthenticationService } from '../../services/authentication.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.page.html',
  styleUrls: ['./login.page.scss'],
})
export class LoginPage implements OnInit {

  constructor(private authService: AuthenticationService) { }

  ngOnInit() {
  }
  login() {
    this.authService.login();
  }

}

register.page.html

代码语言:javascript
复制
<ion-header>
  <ion-toolbar>
    <ion-buttons slot="start">
      <ion-back-button defaultHref="/login"></ion-back-button>
    </ion-buttons>
    <ion-title>Register</ion-title>
  </ion-toolbar>
</ion-header>

<ion-content padding>

</ion-content>

register.page.ts

代码语言:javascript
复制
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-register',
  templateUrl: './register.page.html',
  styleUrls: ['./register.page.scss'],
})
export class RegisterPage implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}

dashboard.page.html

代码语言:javascript
复制
<ion-header>
  <ion-toolbar>
    <ion-buttons slot="start">
      <ion-button (click)="logout()">
        <ion-icon slot="icon-only" name="log-out"></ion-icon>
      </ion-button>
    </ion-buttons>
    <ion-title>My Dashboard</ion-title>
  </ion-toolbar>
</ion-header>

<ion-content padding>

</ion-content>

dashboard.page.ts

代码语言:javascript
复制
import { Component, OnInit } from '@angular/core';
import { AuthenticationService } from '../../services/authentication.service';

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.page.html',
  styleUrls: ['./dashboard.page.scss'],
})
export class DashboardPage implements OnInit {

  constructor(private authService: AuthenticationService) { }

  ngOnInit() {
  }
  logout() {
    this.authService.logout();
  }

}

github源码地址 https://github.com/lilugirl/ionic4_demo

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档