首頁 > web前端 > js教程 > 主體

Angular學習之聊聊Http ( 錯誤處理 / 請求攔截 )

青灯夜游
發布: 2022-12-16 19:36:15
轉載
2328 人瀏覽過

這篇文章帶大家繼續angular的學習,簡單了解一下Angular中的Http處理,介紹一下錯誤處理和請求攔截,希望對大家有所幫助!

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 檔案( 檔案名稱可以隨意)

最主要的是實作HttpInterceptorintercept 方法

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, next: HttpHandler): Observable> {
    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中文網其他相關文章!

相關標籤:
來源:juejin.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!