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. JDBC注册驱动程序的三种方式

    1. Class.forName("com.mysql.jdbc.Driver");//加载数据库驱动 Class.forName("com.mysql.jdbc.Dri ...

  2. CoreThink主题开发(七)使用H-ui开发博客主题之新闻资讯正文页面

    感谢H-ui.感谢CoreThink! 效果图: 后台发文章有上传附件.封面的功能,但是前台代码中有,不能显示,去除了,前台页面还有社会化分享,百度的,页面也不显示. Blog/Cms/Index/d ...

  3. 【转】Git介绍

    版本控制 说到版本控制,脑海里总会浮现大学毕业是写毕业论文的场景,你电脑上的毕业论文一定出现过这番景象! 毕业论文_初稿.doc 毕业论文_修改1.doc 毕业论文_修改2.doc 毕业论文_修改3. ...

  4. mysql ERROR 1045 (28000): Access denied (using password: YES)

    mysql 安装完成后 mysql -u root -p #让输入密码直接回车就能登录 设置mysql的root用户初始密码: mysqladmin -u root password 'root' 解 ...

  5. 用matlab将nc数据读出来,写成二进制文件,然后用grads画图

    clear,clc nt=735;ny=73;    %2.5*2.5格点的nx=144;    %2.5*2.5格点的f=netcdf('air.mon.mean.nc','nowrite');tt ...

  6. OpenGL帧缓存对象(FBO:Frame Buffer Object)

    http://blog.csdn.net/dreamcs/article/details/7691690 转http://blog.csdn.net/xiajun07061225/article/de ...

  7. jQuery带缩略图焦点图插件

    在线演示 本地下载

  8. 在shell中使用sendmail发送邮件

    cat > sendmymail.sh #!/bin/bash/usr/sbin/sendmail -t <<EOFFrom: Mail testing <abc@gmail. ...

  9. iOS Font

    1. 非常棒的查看字体样貌网站: http://iosfonts.com 1. 查看设备支持字体: NSArray *familyNames = [NSMutableArray arrayWithAr ...

  10. centos下安装python2.7.9和pip以及数据科学常用的包

    以前一直用ubantu下的python,ubantu比较卡.自己倾向于使用centos,但默认的python版本太低,所以重新装了一个python和ipython centos6.5安装python2 ...