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"路径。

相关内容

热门资讯

原先有辅助"aapo... 【亲,aapoker透视脚本 这款游戏可以开挂的,确实是有挂的,很多玩家在这款aapoker透视脚本...
透视规律!八闽掌上十八卦脚本,... 透视规律!八闽掌上十八卦脚本,werplan透视挂(透视)开挂辅助挂线上教程;亲,八闽掌上十八卦脚本...
本然有辅助"九江讨赏... 九江讨赏插件 无需打开直接搜索微信:136704302本司针对手游进行,选择我们的四大理由: 1、软...
秘籍开挂"皮皮游戏挂... 秘籍开挂"皮皮游戏挂机辅助"开挂(脚本)辅助脚本(有挂总结);无需打开直接搜索薇:136704302...
素来有开挂"微信传送... >>您好:微信传送屋辅助器下载确实是有挂的,很多玩家在这款微信传送屋辅助器下载游戏中打牌都会发现很多...
透视黑科技!宝宝浙江游戏开挂器... 透视黑科技!宝宝浙江游戏开挂器,微乐小程序辅助开发透视(透视)开挂辅助平台透明挂教程这是一款可以让一...
先前有辅助"欢乐达人... 先前有辅助"欢乐达人程序源码"详细开挂辅助挂有挂秘诀(黑科技教程);无需打开直接搜索微信(13670...
诀窍辅助"哥哥打大a... 诀窍辅助"哥哥打大a外卦辅助工具"开挂(攻略)辅助下载(有挂猫腻) 了解更多开挂安装加(136704...
原先有辅助"新道游透... 新道游透视脚本免费下载是一款专注玩家量身打造的游戏记牌类型软件,在新道游透视脚本免费下载这款游戏中我...
透视私人局!多乐跑辅助得快,h... 较多好评“微乐万能挂官网”开挂(透视)辅助教程 了解更多开挂安装加(136704302)微信号是一款...