本篇文章帶大家繼續(xù)angular的學(xué)習(xí),簡(jiǎn)單了解一下Angular中的Http處理,介紹一下錯(cuò)誤處理和請(qǐng)求攔截,希望對(duì)大家有所幫助!

基本使用
用 Angular 提供的 HttpClient 可以很輕松的實(shí)現(xiàn) API 接口的訪問(wèn)。
舉個(gè)例子 新建一個(gè) http.service.ts 可以在 environment 中配置不同環(huán)境的 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);
}
}
}然后在業(yè)務(wù)中 我們就可以這樣使用
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);
}
}這看起來(lái)非常簡(jiǎn)單 類(lèi)似 Axios
下面介紹一下一些常用的用法
錯(cuò)誤處理
this.http
.echoCode('get', { code: 200 })
.pipe(catchError((err: HttpErrorResponse) => of(err)))
.subscribe((x) => {
if (x instanceof HttpErrorResponse) {
// do something
} else {
// do something
}
});請(qǐng)求攔截
請(qǐng)求攔截是比較常用的
例如 你可以在這里判斷 cookie 是否有效 / 全局錯(cuò)誤處理 ...
新建 http-interceptor.ts 文件 ( 文件名可以隨意 )
最主要的是要實(shí)現(xiàn) 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 中使用 這個(gè)攔截器就生效了
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: HttpInterceptorService,
multi: true,
},
],
})
export class XXXModule {}





