• @angular/cli项目构建--路由2


    app.module.ts update

    const routes: Routes = [
      {path: '', redirectTo: '/home', pathMatch: 'full'},
      {path: 'home', component: HomeComponent},
      {path: 'login', component: LoginComponent},
      {path: '**', component: Code404Component}
    ];

    nav-bar.compoonent.html update

    <ul class="nav navbar-nav navbar-right" *ngIf="!isLogin()">
            <li><a href="#"><span class="glyphicon glyphicon-user"></span> Sign Up</a></li>
            <li><a routerLink="/login"><span class="glyphicon glyphicon-log-in"></span> Login</a></li>
          </ul>
          <ul class="nav navbar-nav navbar-right" *ngIf="isLogin()">
            <li><a href="#"><span class="glyphicon glyphicon-user"></span> {{username}}</a></li>
            <li><a (click)="loginOut()"><span class="glyphicon glyphicon-log-out"></span> LoginOut</a></li>
          </ul>

    login.component.html add

    <div class="container">
      <div class="main-box col-md-6 col-md-offset-3">
    
        <div class="panel panel-info">
          <div class="panel-heading">
            <div class="panel-title">Login</div>
          </div>
    
          <div style="padding:30px" class="panel-body">
    
            <div style="display:none" id="login-alert" class="alert alert-danger col-sm-12"></div>
    
            <form class="form-horizontal" role="form" #loginForm="ngForm"
                  (ngSubmit)="loginForm.form.valid && login()">
    
              <label style="padding-bottom:10px" class="control-label">UserName</label>
              <div style="margin-bottom: 15px" class="input-group"
                   [ngClass]="{'has-error': loginForm.submitted && !username.valid }">
                <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
                <input type="text" class="form-control" name="username" placeholder="username or email"
                       [(ngModel)]="model.username" #username="ngModel" required>
                <div *ngIf="loginForm.submitted && !username.valid" class="help-block">
                  Username is required
                </div>
              </div>
    
              <label style="padding-bottom:10px" class="control-label">Password</label>
              <div style="margin-bottom: 25px" class="input-group"
                   [ngClass]="{'has-error': loginForm.submitted && !username.valid }">
                <span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>
                <input type="password" class="form-control" name="password" placeholder="password"
                       [(ngModel)]="model.password" #password="ngModel" required>
                <div *ngIf="loginForm.submitted && !password.valid" class="help-block">
                  password is required
                </div>
              </div>
              <div class="form-group">
                <button [disabled]="loading" class="btn btn-primary">Login</button>
                <img *ngIf="loading" src="data:image/gif;base64,R0lGODlhEAAQAPIAAP///wAAAMLCwkJCQgAAAGJiYoKCgpKSkiH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAADMwi63P4wyklrE2MIOggZnAdOmGYJRbExwroUmcG2LmDEwnHQLVsYOd2mBzkYDAdKa+dIAAAh+QQJCgAAACwAAAAAEAAQAAADNAi63P5OjCEgG4QMu7DmikRxQlFUYDEZIGBMRVsaqHwctXXf7WEYB4Ag1xjihkMZsiUkKhIAIfkECQoAAAAsAAAAABAAEAAAAzYIujIjK8pByJDMlFYvBoVjHA70GU7xSUJhmKtwHPAKzLO9HMaoKwJZ7Rf8AYPDDzKpZBqfvwQAIfkECQoAAAAsAAAAABAAEAAAAzMIumIlK8oyhpHsnFZfhYumCYUhDAQxRIdhHBGqRoKw0R8DYlJd8z0fMDgsGo/IpHI5TAAAIfkECQoAAAAsAAAAABAAEAAAAzIIunInK0rnZBTwGPNMgQwmdsNgXGJUlIWEuR5oWUIpz8pAEAMe6TwfwyYsGo/IpFKSAAAh+QQJCgAAACwAAAAAEAAQAAADMwi6IMKQORfjdOe82p4wGccc4CEuQradylesojEMBgsUc2G7sDX3lQGBMLAJibufbSlKAAAh+QQJCgAAACwAAAAAEAAQAAADMgi63P7wCRHZnFVdmgHu2nFwlWCI3WGc3TSWhUFGxTAUkGCbtgENBMJAEJsxgMLWzpEAACH5BAkKAAAALAAAAAAQABAAAAMyCLrc/jDKSatlQtScKdceCAjDII7HcQ4EMTCpyrCuUBjCYRgHVtqlAiB1YhiCnlsRkAAAOwAAAAAAAAAAAA=="
                />
              </div>
            </form>
          </div>
        </div>
    
      </div>
    </div>

    login.component.ts add

    import {Component, OnInit} from '@angular/core';
    import {ActivatedRoute, Router} from '@angular/router';
    import {AuthenticationService} from '../authority-guard/authentication.service';
    
    @Component({
      selector: 'app-login',
      templateUrl: './login.component.html',
      styleUrls: ['./login.component.css']
    })
    export class LoginComponent implements OnInit {
    
      model: any = {};
      loading = false;
      returnUrl: string;
    
      constructor(private activeRoute: ActivatedRoute,
                  private router: Router,
                  private authenticationService: AuthenticationService) {
      }
    
      ngOnInit() {
        this.authenticationService.loginOut();
        if (this.authenticationService.login(this.model.username, this.model.password)) {
          this.router.navigate([this.returnUrl]);
        } else {
          this.loading = false;
        }
      }
    
      login() {
        const isLogin = this.authenticationService.login(this.model.username, this.model.password);
        if (isLogin) {
          this.router.navigate(['/home']);
        }
      }
    
    }

    login-auth.service.ts add

    import {Injectable} from '@angular/core';
    import {ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot} from '@angular/router';
    import {AuthenticationService} from '../authority-guard/authentication.service';
    
    @Injectable()
    export class LoginAuthService implements CanActivate {
      constructor(private router: Router,
                  private authenticationService: AuthenticationService) {
      }
    
      canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        // 未登陆,重定向URL到登录页面,包含返回URL参数,然后返回False
        this.router.navigate(['/login'], {queryParams: {returnUrl: state.url}});
        return !!this.authenticationService.isLogin();
      }
    }

    authentication.service.ts add

    import {Injectable} from '@angular/core';
    
    @Injectable()
    export class AuthenticationService {
    
      static isLogin() {
        return localStorage.getItem('currentUser');
      }
    
      static login(username: string, password: string) {
        if (username === 'admin' && password === 'admin') {
          localStorage.setItem('currentUser', username);
          return true;
        }
        return false;
      }
    
      static loginOut() {
        localStorage.removeItem('currentUser');
      }
    }
  • 相关阅读:
    efibootmgr命令
    GPT+UEFI双系统引导
    关于元类的一些使用心得
    队列的数组实现
    队列的链表实现
    栈的链表实现
    栈的数组实现
    单链表实现基数排序
    多项式ADT加法乘法——单链表实现
    LeetCode: 476 Number Complement(easy)
  • 原文地址:https://www.cnblogs.com/Nyan-Workflow-FC/p/7820306.html
Copyright © 2020-2023  润新知