Home > Web Front-end > JS Tutorial > body text

Angular Learning Chat Http (Error Handling/Request Intercepting)

青灯夜游
Release: 2022-12-16 19:36:15
forward
2327 people have browsed it

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"
    }
  }
}
Copy after login
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);
    }
  }
}
Copy after login

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);
  }
}
Copy after login

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
    }
  });
Copy after login

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, next: HttpHandler): Observable> {
    return next
      .handle(req)
      .pipe(filter((event) => event instanceof HttpResponse))
      .pipe(
        catchError((error) => {
          console.log('catch error', error);
          return of(error);
        })
      );
  }
}
Copy after login

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 {}
Copy after login

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!

Related labels:
source:juejin.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!