Angular學習之聊聊Http ( 錯誤處理 / 請求攔截 )
這篇文章帶大家繼續angular的學習,簡單了解一下Angular中的Http處理,介紹一下錯誤處理和請求攔截,希望對大家有所幫助!
基本上使用
用 Angular 提供的 HttpClient 可以很輕鬆的實作 API 介面的存取。 【相關教學推薦:《angular教學》】
舉例新建一個http.service.ts
可以在environment
中設定不同環境的host 位址
再貼一次proxy.config.json
第一章有介紹到
{ "/api": { "target": "http://124.223.71.181", "secure": true, "logLevel": "debug", "changeOrigin": true, "headers": { "Origin": "http://124.223.71.181" } } }
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { environment } from '@env'; @Injectable({ providedIn: 'root' }) export class HttpService { constructor(private http: HttpClient) {} public echoCode(method: 'get' | 'post' | 'delete' | 'put' | 'patch' = 'get', params: { code: number }) { switch (method) { case 'get': case 'delete': return this.http[method](`${environment.backend}/echo-code`, { params }); case 'patch': case 'put': case 'post': return this.http[method](`${environment.backend}/echo-code`, params); } } }
然後在業務中我們就可以這樣使用
import { Component, OnInit } from '@angular/core'; import { HttpService } from './http.service'; @Component({ selector: 'http', standalone: true, templateUrl: './http.component.html', }) export class HttpComponent implements OnInit { constructor(private http: HttpService) {} ngOnInit(): void { this.http.echoCode('get', { code: 200 }).subscribe(console.log); this.http.echoCode('post', { code: 200 }).subscribe(console.log); this.http.echoCode('delete', { code: 301 }).subscribe(console.log); this.http.echoCode('put', { code: 403 }).subscribe(console.log); this.http.echoCode('patch', { code: 500 }).subscribe(console.log); } }
這看起來非常簡單類似Axios
下面介紹一些常用的用法
錯誤處理
this.http .echoCode('get', { code: 200 }) .pipe(catchError((err: HttpErrorResponse) => of(err))) .subscribe((x) => { if (x instanceof HttpErrorResponse) { // do something } else { // do something } });
請求攔截
請求攔截是比較常用的
例如你可以在這裡判斷cookie 是否有效/ 全域錯誤處理...
新http-interceptor.ts
檔案( 檔案名稱可以隨意)
最主要的是實作HttpInterceptor
的intercept
方法
import { HttpInterceptor, HttpRequest, HttpHandler, HttpResponse, HttpErrorResponse } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable, of, throwError } from 'rxjs'; import { filter, catchError } from 'rxjs/operators'; import { HttpEvent } from '@angular/common/http'; @Injectable() export class HttpInterceptorService implements HttpInterceptor { constructor() {} intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { return next .handle(req) .pipe(filter((event) => event instanceof HttpResponse)) .pipe( catchError((error) => { console.log('catch error', error); return of(error); }) ); } }
然後在module 中的providers 中使用這個攔截器就生效了
@NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule], providers: [ { provide: HTTP_INTERCEPTORS, useClass: HttpInterceptorService, multi: true, }, ], }) export class XXXModule {}
更多程式相關知識,請造訪:程式設計教學! !
以上是Angular學習之聊聊Http ( 錯誤處理 / 請求攔截 )的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

熱門話題

基於無阻塞、事件驅動建立的Node服務,具有記憶體消耗低的優點,非常適合處理海量的網路請求。在海量請求的前提下,就需要考慮「記憶體控制」的相關問題了。 1. V8的垃圾回收機制與記憶體限制 Js由垃圾回收機

在當今前端開發中,Vue.js 已經成為了一個非常流行的框架。隨著 Vue.js 的不斷發展,單元測試變得越來越重要。今天,我們將探討如何在 Vue.js 3 中編寫單元測試,並提供一些最佳實踐和常見的問題及解決方案。

文件模組是對底層文件操作的封裝,例如文件讀寫/打開關閉/刪除添加等等文件模組最大的特點就是所有的方法都提供的**同步**和**異步**兩個版本,具有sync 字尾的方法都是同步方法,沒有的都是異

PHP與Vue:完美搭檔的前端開發利器在當今網路快速發展的時代,前端開發變得愈發重要。隨著使用者對網站和應用的體驗要求越來越高,前端開發人員需要使用更有效率和靈活的工具來創建響應式和互動式的介面。 PHP和Vue.js作為前端開發領域的兩個重要技術,搭配起來可以稱得上是完美的利器。本文將探討PHP和Vue的結合,以及詳細的程式碼範例,幫助讀者更好地理解和應用這兩

跨域是開發中常會遇到的場景,也是面試中常會討論的問題。掌握常見的跨域解決方案及其背後的原理,不僅可以提高我們的開發效率,還能在面試中表現的更加

在前端開發面試中,常見問題涵蓋廣泛,包括HTML/CSS基礎、JavaScript基礎、框架和函式庫、專案經驗、演算法和資料結構、效能最佳化、跨域請求、前端工程化、設計模式以及新技術和趨勢。面試官的問題旨在評估候選人的技術技能、專案經驗以及對行業趨勢的理解。因此,應試者應充分準備這些方面,以展現自己的能力和專業知識。

一開始的時候 JS 只在瀏覽器端運行,對於 Unicode 編碼的字串容易處理,但對於二進位和非 Unicode 編碼的字串處理困難。並且二進制是電腦最底層的資料格式,視訊/音訊/程式/網路包

隨著網路技術的發展,前端開發變得日益重要。尤其是行動端設備的普及,更需要高效率、穩定、安全又易於維護的前端開發技術。而作為一門快速發展的程式語言,Go語言已經被越來越多的開發者所使用。那麼,使用Go語言進行前端開發行得通嗎?接下來,本文將為你詳細說明如何使用Go語言進行前端開發。先來看看為什麼要使用Go語言進行前端開發。很多人認為Go語言是一門
