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');
}
}

@angular/cli项目构建--路由2的更多相关文章

  1. @angular/cli项目构建--路由3

    路由定位: modifyUser(user) { this.router.navigate(['/auction/users', user.id]); } 路由定义: {path: 'users/:i ...

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

    app.module.ts import {BrowserModule} from '@angular/platform-browser'; import {NgModule} from '@angu ...

  3. @angular/cli项目构建--组件

    环境:nodeJS,git,angular/cli npm install -g cnpm --registry=https://registry.npm.taobao.org cnpm instal ...

  4. @angular/cli项目构建--modal

    环境准备: cnpm install ngx-bootstrap-modal --save-dev impoerts: [BootstrapModalModule.forRoot({container ...

  5. @angular/cli项目构建--Dynamic.Form

    导入所需模块: ReactiveFormsModule DynamicFormComponent.html <div [formGroup]="form"> <l ...

  6. @angular/cli项目构建--animations

    使用方法一(文件形式定义): animations.ts import { animate, AnimationEntryMetadata, state, style, transition, tri ...

  7. @angular/cli项目构建--interceptor

    JWTInterceptor import {Injectable} from '@angular/core'; import {HttpEvent, HttpHandler, HttpInterce ...

  8. @angular/cli项目构建--httpClient

    app.module.ts update imports: [ HttpClientModule] product.component.ts import {Component, OnInit} fr ...

  9. @angular/cli项目构建--Dynamic.Form(2)

    form-item-control.service.ts update @Injectable() export class FormItemControlService { constructor( ...

随机推荐

  1. [转载]在服务器端判断request来自Ajax请求(异步)还是传统请求(同步),x-requested-with XMLHttpRequest

    在服务器端判断request来自Ajax请求(异步)还是传统请求(同步) 在服务器端判断request来自Ajax请求(异步)还是传统请求(同步):  两种请求在请求的Header不同,Ajax 异步 ...

  2. vloatile总结与synchronized对比

    原文地址:https://www.cnblogs.com/xiaoxian1369/p/5411877.html 1.要使volatile变量提供理想的线程安全,必须同时满足以下两个条件:1).对变量 ...

  3. ansible的主机变量

    ansible的主机变量(常用):ansible_ssh_host     #用于指定被管理的主机的真实IPansible_ssh_port     #用于指定连接到被管理主机的ssh端口号,默认是2 ...

  4. mssql 中文乱码 字库集 问题解决方法

    The database could not be exclusively locked to perform the operation(SQL Server 5030错误解决办法)   SQL S ...

  5. Java基础教程:泛型基础

    Java基础教程:泛型基础 引入泛型 传统编写的限制: 在Java中一般的类和方法,只能使用具体的类型,要么是基本数据类型,要么是自定义类型.如果要编写可以应用于多种类型的代码,这种刻板的限制就会束缚 ...

  6. Web前端开发人员和设计师必读文章推荐【系列十】

    <Web前端开发人员和设计师必读文章推荐系列十>给大家带来最近两个月发布在<梦想天空>的优秀文章,特别推荐给 Web 开发人员和设计师阅读.梦天空博客关注 前端开发 技术,展示 ...

  7. 转:USB枚举

  8. Hibernate关联关系的CRUD

    本文以Group和User(一对多.多对一)双向关联为例,介绍关联关系的CRUD   下面先介绍两个属性 cascade:只影响CRUD中的CUD,即存储(save).更新(update).删除(de ...

  9. Linux文件系统管理 挂载命令mount

    概述 mount命令用来挂载Linux系统外的文件. Linux 中所有的存储设备都必须挂载之后才能使用,包括硬盘.U 盘和光盘(swap 分区是系统直接调用的,所以不需要挂载).不过,硬盘分区在安装 ...

  10. 自定义美化UL OL发光列表

    在线演示 本地下载