Angular Learning Chat Http(오류 처리/요청 차단)

青灯夜游
풀어 주다: 2022-12-16 19:36:15
앞으로
2491명이 탐색했습니다.

이 기사에서는 계속해서 Angle을 배우고, Angular의 Http 처리를 간략하게 이해하고, 오류 처리 및 요청 차단을 소개하는 것이 모든 사람에게 도움이 되기를 바랍니다.

Angular Learning Chat Http(오류 처리/요청 차단)

기본 사용법

Angular에서 제공하는 HttpClient를 사용하면 API 인터페이스에 쉽게 접근할 수 있습니다. [추천 관련 튜토리얼: "angular tutorial"]

예를 들어 새로운 http.service.ts를 생성하면 environment에서 다양한 환경의 호스트 주소를 구성할 수 있습니다. >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

다시 게시하세요 proxy.config.json 1장에서 소개한 내용입니다

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);
        })
      );
  }
}
로그인 후 복사
@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: HttpInterceptorService,
      multi: true,
    },
  ],
})
export class XXXModule {}
로그인 후 복사
그러면 비즈니스에서 이렇게 사용할 수 있습니다

rrreee아주 간단하고 Axios와 유사해 보입니다

다음은 몇 가지 일반적인 사용법입니다🎜

🎜오류 처리🎜🎜rrreee

🎜요청 차단🎜🎜🎜요청 차단 is 더 일반적으로 사용됩니다🎜🎜예를 들어 여기에서 쿠키가 유효한지/전역 오류 처리인지 판단할 수 있습니다...🎜🎜새 http-interceptor.ts 파일을 만듭니다(파일 이름은 임의로 지정할 수 있음). )🎜🎜가장 중요한 것은 HttpInterceptor🎜rrreee🎜의 intercept 메서드를 구현하는 것입니다. 그런 다음 모듈의 공급자에서 이 인터셉터를 사용하여 적용합니다🎜rrreee🎜자세한 내용은 프로그래밍 관련 지식은 🎜프로그래밍 교육 🎜을 방문하세요! ! 🎜

위 내용은 Angular Learning Chat Http(오류 처리/요청 차단)의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:juejin.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!