前端(vue)入門到精通課程,老師線上輔導:聯絡老師
Apipost = Postman + Swagger + Mock + Jmeter 超好用的API偵錯工具:
用 Angular 提供的 HttpClient 可以很輕鬆的實現 API 介面的存取。【相關教學推薦:《》】
舉個例子 新建一個 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 ( 錯誤處理 / 請求攔截 )的詳細內容,更多請關注TW511.COM其它相關文章!