6-7.Angular 入門教學 - 利用路由事件做一個換頁讀取進度條

Angular 入門教學


接著上一篇,我們做好了預載資料,但在預載時如果畫面都沒有任何提示,就會降低使用者體驗

因此我們可以在路由切換頁面時,加上一個讀取條

首先我們先建立一個新的元件

ng g m process-bar
ng g c process-bar

接著我這邊簡單寫了一個css

.loader {
    width: 100%;
    height: 4.8px;
    display: block;
    position: fixed;
    z-index: 100;
    background: rgb(230, 240, 255);
    overflow: hidden;
    top:0;
    
    .bar {
        content: '';
        box-sizing: border-box;
        width: 0;
        height: 4.8px;
        background: rgb(93, 111, 250);
        position: absolute;
        top: 0;
        left: 0;
    }
}

process.component.html

<span class="loader" *ngIf="show">
    <span class="bar" [@startEnd]="status"></span>
</span>

process.component.ts

import { animate, state, style, transition, trigger } from '@angular/animations';
import { Component, OnInit } from '@angular/core';
import { NavigationEnd, NavigationStart, Router } from '@angular/router';
import { filter } from 'rxjs';

@Component({
  selector: 'app-process-bar',
  animations: [
    trigger('startEnd', [
      state('start', style({
        width: '0%'
      })),
      state('80', style({
        width: '80%'
      })),
      state('end', style({
        width: '100%'
      })),
      transition('* => 80', [
        animate('10s')
      ]),
      transition('* => end', [
        animate('0.3s')
      ]),
      transition('* => start', [
        animate('0s')
      ]),
    ]),
  ],
  templateUrl: './process-bar.component.html',
  styleUrls: ['./process-bar.component.scss']
})
export class ProcessBarComponent implements OnInit {
  status = 'start';
  show = false;

  constructor(private router: Router) { }

  ngOnInit(): void {
    this.router.events.pipe(filter(event => event instanceof NavigationStart))
      .subscribe(() => {
        this.status = 'start';
        this.show = true;
        this.status = '80';
      });

    this.router.events.pipe(filter(event => event instanceof NavigationEnd))
      .subscribe(() => {
        this.status = 'end';
        setTimeout(() => {
          this.status = 'start';
          this.show = false;
        }, 300);
        window.scrollTo(0, 0);
      });
  }
}

那這邊就依賴注入Router然後在初始化的時候,訂閱他的events,在分別用filter過濾是路由切換頁面開始跟結束分別做不同事

那上面animations是angular裡面動畫的語法,這以後有機會再講

總之程式很簡單,就是當切換路由開始時,顯示進度條,寬度開始慢慢增加

當路由結束切換頁面時進度條寬度增加到100%後消失,這邊我順便也讓卷軸到最上方,因為換頁通常會在最上方

最後是模組的設定,設定完後記得在app-routing.module.ts中import這個模組才能用

process-bar.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ProcessBarComponent } from './process-bar.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

@NgModule({
  declarations: [
    ProcessBarComponent
  ],
  imports: [
    CommonModule,
    BrowserAnimationsModule
  ],
  exports: [ProcessBarComponent]
})
export class ProcessBarModule { }

有了提示後,使用者知道現在正在讀取中,就會有正常良好的使用者體驗

這篇就很簡單的介紹有這個事件可以利用,至於該做成怎麼樣,就給大家自由發揮

 

範例檔:下載




Copyright © 凱哥寫程式 2022 | Powered by TalllKai ❤