Angular 5 http拦截器没有拦截

时间:2018-03-05 09:31:06

标签: angular angular-http-interceptors

我有一个存储在本地存储中的正确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经验来正确调试它。

任何帮助都会得到很多赞赏。

1 个答案:

答案 0 :(得分:4)

你在这里错误地做了几件事:

拦截器与HttpClientModule一起使用,而不是与HttpModule一起使用。您正在使用python manage.py migrate。您需要更改为HttpModule

  1. HttpClientModule
  2. 中的导入数组中添加HttpClientModule
  3. app.module.ts中导入HttpClient并在其构造函数中对其进行引用。
  4. 参考下面的代码:

    authentication.service.ts

      //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 { }
    

    在authentication.service.ts

    中进行类似的更改
相关问题