@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‘);
  }
}
时间: 2024-10-09 09:49:10

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

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

app.module.ts import {BrowserModule} from '@angular/platform-browser'; import {NgModule} from '@angular/core'; import {AppComponent} from './app.component'; import {NavBarComponent} from './nav-bar/nav-bar.component'; import {FooterComponent} from '.

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

环境:nodeJS,git,angular/cli npm install -g cnpm cnpm install -g @angular/cli ng new angularDemo ng -v ng set --global packageManager=cnpm npm install jquery --save npm install bootstrap --save npm install @type/jquery --save-dev npm install @type/boots

@angular/cli项目构建--httpClient

app.module.ts update imports: [ HttpClientModule] product.component.ts import {Component, OnInit} from '@angular/core'; import {HttpClient} from '@angular/common/http'; import {Observable} from 'rxjs/Observable'; import * as _ from 'lodash'; @Compone

@angular/cli项目构建--modal

环境准备: cnpm install ngx-bootstrap-modal --save-dev impoerts: [BootstrapModalModule.forRoot({container: ducument.body})] usage: import { Component } from '@angular/core'; import { DialogService } from "ngx-bootstrap-modal"; @Component({ selector:

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

导入所需模块: ReactiveFormsModule DynamicFormComponent.html <div [formGroup]="form"> <label [attr.for]="formItem.key">{{formItem.label}}</label> <div [ngSwitch]="formItem.controlType"> <input *ngSwitchCas

Angular Cli 设置 淘宝的NPM 镜像

Angular CLI 是 构建angular2 项目的 脚手架工具. 安装Angular-Cli  需要先安装 Node.js. 大家可以去 node.js 官网下载. 说明:因为npm安装插件是从国外服务器下载,受网络影响大,可能出现异常.所以我们需要适用淘宝的镜像. http://registry.npm.taobao.org/ 设置方法如下:npm install -g cnpm  --registry=https://registry.npm.taobao.org 然后使用 cnpm 

Angular CLI的简单使用(2)

刚才创建了myApp这个项目,看一下这个项目的文件结构.    项目文件概览 Angular CLI项目是做快速试验和开发企业解决方案的基础. 你首先要看的文件是README.md. 它提供了一些如何使用CLI命令的基础信息. 如果你想了解 Angular CLI 的工作原理,请访问 Angular CLI 的仓库及其Wiki. 有些生成的文件你可能觉得陌生.接下来就讲讲它们. src文件夹 你的应用代码位于src文件夹中. 所有的Angular组件.模板.样式.图片以及你的应用所需的任何东西都

Angular环境准备和Angular cli

Angular4.0来了,更小,更快,改动少 接下来为Angular4.0准备环境和学会使用Angular cli项目 1.环境准备: 1)在开始工作之前我们必须设置好开发环境 如果你的机器上还没有安装Node.js和npm,请安装他们 (这里特别推荐使用淘宝的镜像cnpm,记得以后把npm的指令改为cnpm就可以了) npm install -g cnpm --registry=https://registry.npm.taobao.org 然后我们可以通过node -v和cnpm -v来分别

内网安装angular/cli

博主在外网搭建angular/cli项目迁移到内网时无法启动npm start,于是找了好多方法探索,因而发现时angular/cli需要全局安装,外网只需要npm i -g @angular/cli就好了,因为有npm帮你去下载:然而我这是在内网开发,于是想破了头找了网上的方法:window上亲测有效 Install Angular CLI Offline Install it in online machine and copy %appdata%/npm/node_modules/@ang