這篇文章帶大家繼續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中文網其他相關文章!