[英]Angular 5 http interceptor not intercepting
我有一个正确的 JWT 令牌存储在本地存储中,还有一个我从教程中公然复制的拦截器。 但是,它不会拦截请求并向请求添加标头。
这是我提出请求的地方:
这是拦截器:
和我的 appmodule - 我很确定它已正确导入:
https://github.com/Marred/Informakcja/blob/master/Informakcja-client/src/app/app.module.ts
当我提出请求时,我希望拦截器记录我指定到控制台的消息并将令牌添加到标头中,但它并没有这样做,我不知道为什么:/我用其他一些教程检查了代码在线并没有看到任何能够破坏我的代码的差异。 我也没有足够的 Angular 经验来正确调试它。
任何帮助将不胜感激。
你在这里做错了几件事:
拦截器与 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 中进行类似的更改
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.