# Day27 【牙起來】 導回上一頁的幾種作法 - Routing ## 導回上一頁 ### `location.back()` - Javascript 作法 修改 `app.component.ts` ```typescript= // 注意是import Angular的Location,而不是Typescrit的 import { Location } from '@angular/common'; // 這行很重要 ... constructor(private location: Location) { } goBack() { this.location.back() // 或者 // window.history.back(); } ``` ### `routerLink` - 樣板帶參數 修改 `app.component.html` ```html= <router-outlet></router-outlet> <button [routerLink]="['role']">點我進role</button> <button [routerLink]="'..'">回上一頁</button> ``` ### Router服務 `router.navigate` - 程式帶參數 ```typescript= ... export class AppComponent { title = 'project04'; constructor(private router: Router) { } goBack() { this.router.navigate(['..']) } } ``` ### `NavigationService` - 自己寫服務 透過`ng cli`產生一個`navigation`服務 > ng g s navigation 用陣列來記錄所有[導頁歷程](https://angular.io/api/router/NavigationEnd),當按下**回上一頁**時`pop()`最後一項 修改`navigation.service.ts` ```typescript= import { Injectable } from '@angular/core'; import { NavigationEnd, Router } from '@angular/router'; import { Location } from '@angular/common'; @Injectable({ providedIn: 'root' }) export class NavigationService { history: string[] = []; constructor(private router: Router, private location: Location) { this.router.events.subscribe(event => { // 偵測所有路由事件 if (event instanceof NavigationEnd) { // 僅當導頁完畢時 this.history.push(event.urlAfterRedirects) // `urlAfterRedirects`為分頁的路徑 } }) } back(): void { let lastPage = this.history.pop(); if (lastPage) { this.location.back(); } else { this.router.navigateByUrl('/'); // 回首頁 } } } ``` > 某些情況下,當重要的頁面**不能讓使用者返回到上一頁**時 > 這時候複雜的邏輯只能靠自己寫服務來控管 > > ex: 可對history `pop()`出來的路徑判斷 **可不可以回上一頁** > 如果是重要的頁面則不給返回、或者再導到更前一頁 修改`app.component.html` ```html= <router-outlet></router-outlet> <button [routerLink]="['role']">點我進role</button> <button [routerLink]="['store']">點我進store</button> <button (click)="goBack()">回上一頁</button> ``` 將服務注入到有切換分頁按鈕的元件中 修改`app.component.ts` ```typescript= import { Component } from '@angular/core'; import { NavigationService } from './navigation.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'project04'; constructor(private navSvc: NavigationService) { } goBack() { this.navSvc.back(); } } ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up