Angular拦截器基于响应将路由到不同的路径
创始人
2024-10-27 22:31:06
0

在Angular中,可以使用拦截器来基于响应将路由到不同的路径。下面是一个示例代码:

首先,创建一个名为response-interceptor.ts的拦截器文件,其中包含以下代码:

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import { Router } from '@angular/router';

@Injectable()
export class ResponseInterceptor implements HttpInterceptor {

  constructor(private router: Router) {}

  intercept(request: HttpRequest, next: HttpHandler): Observable> {
    return next.handle(request).pipe(
      tap(response => {
        // 假设当响应的状态码为200时,路由到"/success"路径
        if (response.status === 200) {
          this.router.navigate(['/success']);
        }
      })
    );
  }
}

然后,在app.module.ts文件中,将拦截器添加到提供者列表中:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';

import { AppComponent } from './app.component';
import { ResponseInterceptor } from './response-interceptor';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule
  ],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: ResponseInterceptor,
      multi: true
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

现在,当使用HttpClient发送请求并且接收到200状态码的响应时,Angular将自动使用拦截器将路由导航到"/success"路径。

相关内容

热门资讯

解迷透视!hhpoker德州牛... 解迷透视!hhpoker德州牛仔视频,微乐游戏兑换码大全,要领教程(有挂规律)-哔哩哔哩1、下载好h...
必备透视!wepoker有没有... 必备透视!wepoker有没有挂,微乐小程序黑科技app入口,步骤教程(有挂教学)-哔哩哔哩1、每一...
有挂透视!wepoker怎么开... 有挂透视!wepoker怎么开辅助,微信微乐陕西挖坑小程序下载,窍要教程(有挂秘笈)-哔哩哔哩1、w...
曝光透视!wpk模拟器是什么,... 曝光透视!wpk模拟器是什么,微信小程序微乐破解器,阶段教程(有挂规律)-哔哩哔哩1、上手简单,内置...
解迷透视!wpk透视辅助靠谱吗... 解迷透视!wpk透视辅助靠谱吗,微乐游戏小程序脚本,指南书教程(有挂工具)-哔哩哔哩1、每一步都需要...
解谜透视!哈糖大菠萝有没有挂,... 解谜透视!哈糖大菠萝有没有挂,微乐家乡小程序脚本,方针教程(有挂教学)-哔哩哔哩1、哈糖大菠萝有没有...
分享透视!wepoker私人局... 分享透视!wepoker私人局透视插件,微信小程序游戏破解器,手段教程(真实有挂)-哔哩哔哩1、每一...
解密透视!aapoker ai... 您好,aapoker ai插件这款游戏可以开挂的,确实是有挂的,需要了解加去威信【485275054...
解密透视!拱趴大菠萝作弊方法,... 解密透视!拱趴大菠萝作弊方法,微信微乐跑得快游戏辅助脚本,方针教程(详细教程)-哔哩哔哩1)拱趴大菠...
了解透视!pokemomo辅助... 了解透视!pokemomo辅助软件,微乐河南家乡麻将辅助脚本,策略教程(有挂猫腻)-哔哩哔哩1、po...