【问题标题】:Angular 5 http interceptor not interceptingAngular 5 http拦截器不拦截
【发布时间】:2023-03-13 03:54:01
【问题描述】:

我有一个存储在本地存储中的正确 JWT 令牌和一个我从教程中公然复制的拦截器。但是,它不会拦截请求并将标头添加到请求中。

这里是我提出请求的地方:

https://github.com/Marred/Informakcja/blob/master/Informakcja-client/src/app/services/information.service.ts

这是拦截器:

https://github.com/Marred/Informakcja/blob/master/Informakcja-client/src/app/services/token.interceptor.ts

还有我的 appmodule - 我很确定它已正确导入:

https://github.com/Marred/Informakcja/blob/master/Informakcja-client/src/app/app.module.ts

当我发出请求时,我希望拦截器记录我指定到控制台的消息并将令牌添加到标头,但它并没有这样做,我不知道为什么:/我检查了代码在网上找到的其他教程并没有看到任何能够破坏我的代码的差异。我也没有足够的 Angular 经验来正确调试它。

任何帮助将不胜感激。

【问题讨论】:

  • 链接已失效。

标签: javascript angular typescript angular-http-interceptors


【解决方案1】:

你在这里做错了几件事:

拦截器与 HttpClientModule 一起使用,而不是与 HttpModule 一起使用。您正在使用HttpModule。你需要改成HttpClientModule

  1. app.module.ts 的导入数组中添加HttpClientModule
  2. 在您的authentication.service.ts 中导入HttpClient,并在其构造函数中引用它。

参考以下代码:

  //app.module.ts
    import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
    .
    .
    .
    @NgModule({
      declarations: [
        AppComponent,
       .
       .
       .
      ],
      imports: [
        BrowserModule,
        .
        .
        .,
        HttpClientModule, //add here
        RouterModule.forRoot([
          { path: '', redirectTo: 'home', pathMatch: 'full' },
          { path: 'home', component: HomeComponent },
          { path: 'login', component: LoginComponent },
          { path: 'register', component: RegisterComponent },
          { path: 'add-information', component: AddInformationComponent },
          { path: '**', redirectTo: 'home' }
        ], { useHash: true })
      ],
      providers: [
        { provide: 'BASE_URL', useValue: 'https://some URL/' },
        UserService,
        InformationService,
        AuthenticationService,
        AlertService,
        {
          provide: HTTP_INTERCEPTORS,
          useClass: TokenInterceptor,
          multi: true
        }
      ],
      bootstrap: [AppComponent]
    })
    export class AppModule { }

//information.service.ts and authentication.service.ts

import { Injectable, Inject } from '@angular/core';
import { HttpClient} from '@angular/common/http'; //added import
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';

@Injectable()
export class InformationService {

  constructor(private http: HttpClient, @Inject('BASE_URL') private baseUrl: string) { } //made changes in cunstructor

  add(link: string, title: string, description: string) {
    return this.http.post(this.baseUrl + 'api/Information', { link: link, title: title, description: description })
    .map((response: Response) => {
        console.log(response);
    });
  }
}

在 authentication.service.ts 中进行类似的更改

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-07
    • 2018-05-19
    • 1970-01-01
    • 1970-01-01
    • 2018-07-08
    相关资源
    最近更新 更多