Angular学习之聊聊Http ( 错误处理 / 请求拦截 )

 3002

本篇文章带大家继续angular的学习,简单了解一下Angular中的Http处理,介绍一下错误处理请求拦截,希望对大家有所帮助!


Angular学习之聊聊Http ( 错误处理 / 请求拦截 )


基本使用

用 Angular 提供的 HttpClient 可以很轻松的实现 API 接口的访问。

举个例子 新建一个 http.service.ts 可以在 environment 中配置不同环境的 host 地址

再贴一下 proxy.config.json 第一章中有介绍到

  1. {
  2.   "/api": {
  3.     "target": "http://124.223.71.181",
  4.     "secure": true,
  5.     "logLevel": "debug",
  6.     "changeOrigin": true,
  7.     "headers": {
  8.       "Origin": "http://124.223.71.181"
  9.     }
  10.   }
  11. }
  1. import { HttpClient } from '@angular/common/http';
  2. import { Injectable } from '@angular/core';
  3. import { environment } from '@env';
  4.  
  5. @Injectable({ providedIn: 'root' })
  6. export class HttpService {
  7.   constructor(private http: HttpClient) {}
  8.  
  9.   public echoCode(method: 'get' | 'post' | 'delete' | 'put' | 'patch' = 'get', params: { code: number }) {
  10.     switch (method) {
  11.       case 'get':
  12.       case 'delete':
  13.         return this.http[method](`${environment.backend}/echo-code`, { params });
  14.       case 'patch':
  15.       case 'put':
  16.       case 'post':
  17.         return this.http[method](`${environment.backend}/echo-code`, params);
  18.     }
  19.   }
  20. }

然后在业务中 我们就可以这样使用

  1. import { Component, OnInit } from '@angular/core';
  2. import { HttpService } from './http.service';
  3.  
  4. @Component({
  5.   selector: 'http',
  6.   standalone: true,
  7.   templateUrl: './http.component.html',
  8. })
  9. export class HttpComponent implements OnInit {
  10.   constructor(private http: HttpService) {}
  11.   ngOnInit(): void {
  12.     this.http.echoCode('get', { code: 200 }).subscribe(console.log);
  13.     this.http.echoCode('post', { code: 200 }).subscribe(console.log);
  14.     this.http.echoCode('delete', { code: 301 }).subscribe(console.log);
  15.     this.http.echoCode('put', { code: 403 }).subscribe(console.log);
  16.     this.http.echoCode('patch', { code: 500 }).subscribe(console.log);
  17.   }
  18. }

这看起来非常简单 类似 Axios

下面介绍一下一些常用的用法


错误处理

  1. this.http
  2.   .echoCode('get', { code: 200 })
  3.   .pipe(catchError((err: HttpErrorResponse) => of(err)))
  4.   .subscribe((x) => {
  5.     if (x instanceof HttpErrorResponse) {
  6.       // do something
  7.     } else {
  8.       // do something
  9.     }
  10.   });


请求拦截

请求拦截是比较常用的

例如 你可以在这里判断 cookie 是否有效 / 全局错误处理 ...

新建 http-interceptor.ts 文件 ( 文件名可以随意 )

最主要的是要实现 HttpInterceptor 的 intercept 方法

  1. import { HttpInterceptor, HttpRequest, HttpHandler, HttpResponse, HttpErrorResponse } from '@angular/common/http';
  2. import { Injectable } from '@angular/core';
  3. import { Observable, of, throwError } from 'rxjs';
  4. import { filter, catchError } from 'rxjs/operators';
  5. import { HttpEvent } from '@angular/common/http';
  6.  
  7. @Injectable()
  8. export class HttpInterceptorService implements HttpInterceptor {
  9.   constructor() {}
  10.   intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  11.     return next
  12.       .handle(req)
  13.       .pipe(filter((event) => event instanceof HttpResponse))
  14.       .pipe(
  15.         catchError((error) => {
  16.           console.log('catch error', error);
  17.           return of(error);
  18.         })
  19.       );
  20.   }
  21. }

然后在 module 中的 providers 中使用 这个拦截器就生效了

  1. @NgModule({
  2.   imports: [RouterModule.forChild(routes)],
  3.   exports: [RouterModule],
  4.   providers: [
  5.     {
  6.       provide: HTTP_INTERCEPTORS,
  7.       useClass: HttpInterceptorService,
  8.       multi: true,
  9.     },
  10.   ],
  11. })
  12. export class XXXModule {}


本文网址:https://www.zztuku.com/index.php/detail-13599.html
站长图库 - Angular学习之聊聊Http ( 错误处理 / 请求拦截 )
申明:本文转载于《掘金社区》,如有侵犯,请 联系我们 删除。

评论(0)条

您还没有登录,请 登录 后发表评论!

提示:请勿发布广告垃圾评论,否则封号处理!!

    编辑推荐