你在这里做错了几件事:
拦截器与 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 中进行类似的更改