ng-book札記——路由

来源:https://www.cnblogs.com/kenwoo/archive/2018/04/22/8906041.html
-Advertisement-
Play Games

路由的作用是分隔應用為不同的區塊,每個區塊基於匹配當前URL的規則。 路由可以分為服務端與客戶端兩種,服務端以Express.js為例: 服務端接收請求並路由至一個控制器(controller),控制器執行指定的操作(action)。 客戶端的路由在概念上與服務端相似,其好處是不需要每次URL地址變 ...


路由的作用是分隔應用為不同的區塊,每個區塊基於匹配當前URL的規則。

路由可以分為服務端與客戶端兩種,服務端以Express.js為例:

var express = require('express');
var router = express.Router();

// define the about route
router.get('/about', function(req, res) {
  res.send('About us');
});

服務端接收請求並路由至一個控制器(controller),控制器執行指定的操作(action)。

客戶端的路由在概念上與服務端相似,其好處是不需要每次URL地址變化都將路由請求發送至服務端。

客戶端路由有兩種實現方式:使用傳統的錨(anchor)標簽與HTML5客戶端路由。第一種方式也被稱為hash-based路由,URL的形式如這般:http://something/#/about。第二種依賴HTML5的history.pushState方法,缺點是老舊的瀏覽器不支持這種方式,以及伺服器也必須支持基於HTML5的路由。Angular官方推薦的是後者。

使用Angular路由的方法,首先要導入相關類庫:

import {
    RouterModule,
    Routes
} from '@angular/router';

再配置路由規則:

const routes: Routes = [
  // basic routes
  { path: '', redirectTo: 'home', pathMatch: 'full' },
  { path: 'home', component: HomeComponent },
  { path: 'about', component: AboutComponent },
  { path: 'contact', component: ContactComponent },
  { path: 'contactus', redirectTo: 'contact' }
]

path指定路由所要處理的URL,component綁定相關的組件,redirectTo重定向至已知的路由。

最後在NgModule中引入RouterModule模塊及預設的路由:

imports: [
  BrowserModule,
  FormsModule,
  HttpModule,
  RouterModule.forRoot(routes), // <-- routes

  // added this for our child module
  ProductsModule
]

Angular預設的路由策略是PathLocationStrategy,即基於HTML5的路由。如果想使用HashLocationStrategy,需要在代碼里額外申明。

providers: [
  { provide: LocationStrategy, useClass: HashLocationStrategy }
]

路由上可以帶參數,通過/route/:param的形式。不過這種情況下需要導入ActivatedRoute。

import { ActivatedRoute } from '@angular/router';
const routes: Routes = [
  { path: 'product/:id', component: ProductComponent }
];
export class ProductComponent {
  id: string;

  constructor(private route: ActivatedRoute) {
    route.params.subscribe(params => { this.id = params['id']; });
  }
}

想在頁面中添加跳轉鏈接的話,可以使用[routerLink]指令:

<div class="page-header">
  <div class="container">
  <h1>Router Sample</h1>
  <div class="navLinks">
    <a [routerLink]="['/home']">Home</a>
    <a [routerLink]="['/about']">About Us</a>
    <a [routerLink]="['/contact']">Contact Us</a>
    |
    <a [routerLink]="['/products']">Products</a>
    <a [routerLink]="['/login']">Login</a>
    <a [routerLink]="['/protected']">Protected</a>
    </div>
  </div>
</div>

而如果想要用模板頁面的話,則需要

<div id="content">
  <div class="container">
    <router-outlet></router-outlet>
  </div>
</div>

頁面中的router-outlet元素即是每個路由綁定的組件所渲染內容的位置。

複雜的頁面可能還會需要用到嵌套路由:

const routes: Routes = [
  //nested
  { path: 'products', 
    component: ProductsComponent,
    chilren: [
     { path: '', redirectTo: 'main', pathMatch: 'full' },
     { path: 'main', component: MainComponent },
     { path: 'more-info', component: MoreInfoComponent },
     { path: ':id', component: ProductComponent },
    ] 
  }
]

路由的建立是經由相對路徑來構成,所以需要有配置其基礎路徑位置的地方,一般這個配置會放在index.html頁面的base元素中。

<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Routing</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <app-root>Loading...</app-root>
</body>
</html>

最常見的寫法就是<base href="/">

同時還可以在NgModule中以代碼實現,兩者效果等效:

providers: [
  { provide: APP_BASE_HREF, useValue: '/' } // <--- this right here
]

切換路由時可能會有要求額外的處理工作,比如認證。這種場景下,路由的構子可以派上用處。

import { Injectable } from '@angular/core';

@Injectable()
export class AuthService {
  login(user: string, password: string): boolean {
    if (user === 'user' && password === 'password') {
      localStorage.setItem('username', user);
      return true;
    }

    return false;
  }
  
  logout(): any {
    localStorage.removeItem('username');
  }

  getUser(): any {
    return localStorage.getItem('username');
  }

  isLoggedIn(): boolean {
    return this.getUser() !== null;
  }
}  
export const AUTH_PROVIDERS: Array<any> = [
  { provide: AuthService, useClass: AuthService }
];

import { Injectable } from '@angular/core';
import {
  CanActivate,
  ActivatedRouteSnapshot,
  RouterStateSnapshot
} from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { AuthService } from './auth.service';

@Injectable()
export class LoggedInGuard implements CanActivate {
  constructor(private authService: AuthService) {}

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    const isLoggedIn = this.authService.isLoggedIn();
    console.log('canActivate', isLoggedIn);
    return isLoggedIn;
  }
}
import { AUTH_PROVIDERS } from './auth.service';
import { LoggedInGuard } from './logged-in.guard';

const routes: Routes = [
 {
   path: 'protected',
   component: ProtectedComponent,
   canActivate: [ LoggedInGuard ]
 },
];

上述例子中,當路由至'protected'地址時,'LoggedInGuard'處理類會進入路由調用環路,依據是否已登陸這一信息來決定此次路由是否有效。


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 之前做過一版h5微信聊天移動端,這段時間閑來無事就整理了下之前項目,又重新在原先的那版基礎上升級了下,如是就有了現在的h5仿微信聊天高仿版,新增了微聊、通訊錄、探索、我四個模塊 左右觸摸滑屏切換,聊天頁面優化了多圖預覽、視頻播放,長按菜單UI,聊天底部編輯器重新優化整理(新增多表情),彈窗則用到了自 ...
  • 原文摘自:https://www.cnblogs.com/moqiutao/archive/2015/12/23/5070463.html 總節: 1) 定義字體標準格式: 2)字體轉換網址: http://www.freefontconverter.com/https://everythingfo ...
  • 最近因為工作關係,一直在做node.js的開發,學習了koa框架,orm框架sequelize,以及swagger文檔的配置。但是,最近因為swagger文檔使用了es6的修飾器那麼個東西(在java中被稱作註解),所以,node.js無法編譯項目,所以就需要使用babel對es6進行轉換。因為這篇 ...
  • <!DOCTYPE html><html xmlns="http://www.w3.org/1999/html"><head lang="en"> <meta charset="UTF-8"> <title></title> <link rel="stylesheet" href="../css/r ...
  • var聲明變數的作用域限制在其聲明位置的上下文中 let 聲明的變數只在其聲明的塊或子塊中可用,var的作用域是整個封閉函數 在 ECMAScript 2015 中,let綁定不受變數提升的約束,這意味著let聲明不會被提升到當前執行上下文的頂部。 在塊中的變數初始化之前,引用它將會導致 Refer ...
  • 正則的一些基礎知識 創建正則 通過構造函數 const pattern = new RegExp(pattern,modifiers) pattern: 匹配的字元串形式,可以有變數 modifiers: 匹配的模式,g(全局),i(忽略大小寫),u(多行) 字面量的形式: const patter ...
  • 最近在學習react,然後遇到react中css該怎麼寫這個問題,上知乎上看了好多大牛都說styled-components好用是大勢所趨。 但我自己用了感覺體驗卻很差,我在這裡說說我為啥覺得styled-components不好用。 1.既然用了styled-components,那除了引用全局的 ...
  • HTML內容元素中圖片元素 使用img元素:src屬性:圖片路徑。 alt屬性:圖片無法顯示的時候使用替代文本,title屬性:滑鼠懸停時顯示文本內容。 在同一張圖片上點擊不同的位置鏈接到不同的頁面上 使用map,和area元素(map是area的父元素) 加上id或者name是為瞭解決相容性。 s ...
一周排行
    -Advertisement-
    Play Games
  • 前言 在我們開發過程中基本上不可或缺的用到一些敏感機密數據,比如SQL伺服器的連接串或者是OAuth2的Secret等,這些敏感數據在代碼中是不太安全的,我們不應該在源代碼中存儲密碼和其他的敏感數據,一種推薦的方式是通過Asp.Net Core的機密管理器。 機密管理器 在 ASP.NET Core ...
  • 新改進提供的Taurus Rpc 功能,可以簡化微服務間的調用,同時可以不用再手動輸出模塊名稱,或調用路徑,包括負載均衡,這一切,由框架實現並提供了。新的Taurus Rpc 功能,將使得服務間的調用,更加輕鬆、簡約、高效。 ...
  • 順序棧的介面程式 目錄順序棧的介面程式頭文件創建順序棧入棧出棧利用棧將10進位轉16進位數驗證 頭文件 #include <stdio.h> #include <stdbool.h> #include <stdlib.h> 創建順序棧 // 指的是順序棧中的元素的數據類型,用戶可以根據需要進行修改 ...
  • 前言 整理這個官方翻譯的系列,原因是網上大部分的 tomcat 版本比較舊,此版本為 v11 最新的版本。 開源項目 從零手寫實現 tomcat minicat 別稱【嗅虎】心有猛虎,輕嗅薔薇。 系列文章 web server apache tomcat11-01-官方文檔入門介紹 web serv ...
  • C總結與剖析:關鍵字篇 -- <<C語言深度解剖>> 目錄C總結與剖析:關鍵字篇 -- <<C語言深度解剖>>程式的本質:二進位文件變數1.變數:記憶體上的某個位置開闢的空間2.變數的初始化3.為什麼要有變數4.局部變數與全局變數5.變數的大小由類型決定6.任何一個變數,記憶體賦值都是從低地址開始往高地 ...
  • 如果讓你來做一個有狀態流式應用的故障恢復,你會如何來做呢? 單機和多機會遇到什麼不同的問題? Flink Checkpoint 是做什麼用的?原理是什麼? ...
  • C++ 多級繼承 多級繼承是一種面向對象編程(OOP)特性,允許一個類從多個基類繼承屬性和方法。它使代碼更易於組織和維護,並促進代碼重用。 多級繼承的語法 在 C++ 中,使用 : 符號來指定繼承關係。多級繼承的語法如下: class DerivedClass : public BaseClass1 ...
  • 前言 什麼是SpringCloud? Spring Cloud 是一系列框架的有序集合,它利用 Spring Boot 的開發便利性簡化了分散式系統的開發,比如服務註冊、服務發現、網關、路由、鏈路追蹤等。Spring Cloud 並不是重覆造輪子,而是將市面上開發得比較好的模塊集成進去,進行封裝,從 ...
  • class_template 類模板和函數模板的定義和使用類似,我們已經進行了介紹。有時,有兩個或多個類,其功能是相同的,僅僅是數據類型不同。類模板用於實現類所需數據的類型參數化 template<class NameType, class AgeType> class Person { publi ...
  • 目錄system v IPC簡介共用記憶體需要用到的函數介面shmget函數--獲取對象IDshmat函數--獲得映射空間shmctl函數--釋放資源共用記憶體實現思路註意 system v IPC簡介 消息隊列、共用記憶體和信號量統稱為system v IPC(進程間通信機制),V是羅馬數字5,是UNI ...