Angular怎么实现错误处理和请求拦截

发布时间:2022-12-17 09:45:56 作者:iii
来源:亿速云 阅读:119

本篇内容主要讲解“Angular怎么实现错误处理和请求拦截”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Angular怎么实现错误处理和请求拦截”吧!

基本使用

用 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 文件 ( 文件名可以随意 )

最主要的是要实现 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<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怎么实现错误处理和请求拦截”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

推荐阅读:
  1. ASP.Net Core与Angular的开源实例项目分析
  2. Angular的@Output与@Input怎么理解

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

angular

上一篇:jquery如何判断是否包含某属性

下一篇:go语言的最重要特性有哪些

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》