首页 文章

Angular 5 http拦截器没有拦截

提问于
浏览
-1

我有一个存储在本地存储中的正确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 回答

  • 3

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

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

    • app.module.ts 中的导入数组中添加 HttpClientModule

    • 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中进行类似的更改

相关问题