Home >Web Front-end >JS Tutorial >Angular Learning Chat Http (Error Handling/Request Intercepting)

Angular Learning Chat Http (Error Handling/Request Intercepting)

青灯夜游
青灯夜游forward
2022-12-16 19:36:152544browse

This article will take you to continue learning angular, briefly understand Http processing in Angular, and introduce error handling and request interception. I hope it will be helpful to everyone!

Angular Learning Chat Http (Error Handling/Request Intercepting)

Basic use

Using the HttpClient provided by Angular, you can easily access the API interface. [Related tutorial recommendations: "angular tutorial"]

For example, create a new http.service.ts, which can be configured differently in environment The host address of the environment

Post it againproxy.config.json It was introduced in Chapter 1

{
  "/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);
    }
  }
}

Then we can use it like this in business

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);
  }
}

This looks very simple and similarAxios

Here are some common usages

Error handling

this.http
  .echoCode('get', { code: 200 })
  .pipe(catchError((err: HttpErrorResponse) => of(err)))
  .subscribe((x) => {
    if (x instanceof HttpErrorResponse) {
      // do something
    } else {
      // do something
    }
  });

Request interception

Request interception is more commonly used

For example, you can determine whether the cookie is valid/global error handling here...

New http-interceptor.ts File (the file name can be arbitrary)

The most important thing is to implement the intercept method of HttpInterceptor

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(&#39;catch error&#39;, error);
          return of(error);
        })
      );
  }
}

Then use this interceptor in the providers in the module to take effect

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: HttpInterceptorService,
      multi: true,
    },
  ],
})
export class XXXModule {}

For more programming-related knowledge, please visit: Programming Tutorial! !

The above is the detailed content of Angular Learning Chat Http (Error Handling/Request Intercepting). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete