Reputation: 1320
I am trying to implement HttpCache through interceptor. Following is the caching-interceptor.service.ts
import { HttpRequest, HttpResponse, HttpInterceptor, HttpHandler, HttpEvent } from '@angular/common/http'
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';
import 'rxjs/add/observable/of';
export abstract class HttpCache {
abstract get(req: HttpRequest<any>): HttpResponse<any>|null;
abstract put(req: HttpRequest<any>, resp: HttpResponse<any>): void;
}
@Injectable()
export class CachingInterceptor implements HttpInterceptor {
constructor(private cache: HttpCache) {}
intercept(req: HttpRequest<any>, next: HttpHandler) : Observable<HttpEvent<any>> {
if(req.method !== 'GET'){
return next.handle(req);
}
const cachedResponse = this.cache.get(req);
if(cachedResponse){
return Observable.of(cachedResponse);
}
return next.handle(req).do(event => {
if(event instanceof HttpResponse){
this.cache.put(req, event);
}
})
}
}
and I am calling from test.service.ts
import { Injectable } from '@angular/core';
import { Headers, Http, Response} from '@angular/http';
import { HttpClient} from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { ReplaySubject } from 'rxjs/ReplaySubject';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { APIService } from './api.service';
import { CachingInterceptor } from './caching-interceptor.service';
import { ConfigurationService } from './configuration.service';
import { AuthenticationStatus, IAuthenticationStatus } from '../models';
import { User } from '../models/user.model';
@Injectable()
export class PlatformService extends APIService {
constructor(private http: Http, public httpClient: HttpClient, private configuration: ConfigurationService,
public cachingInterceptor: CachingInterceptor) {
super();
}
getUserById(id: string) {
console.log(this.requestOptions);
return this.httpClient.get(this._getAPIUrl('user/' + id),this.requestOptions).
subscribe(res => res);
}
get requestOptions(): RequestOptions {
const tokenObj = window.localStorage.getItem('TOKEN');
const token = JSON.parse(tokenObj);
const headers = this.headers;
headers.append('Authorization', 'Bearer ' + token.token);
headers.append('Access-Control-Allow-Origin', '*');
return new RequestOptions({ headers: headers });
}
}
and Module file is following
import { CommonModule } from '@angular/common';
import { HTTP_INTERCEPTORS, HttpClient } from '@angular/common/http';
import { FormsModule } from '@angular/forms';
import { ModuleWithProviders, NgModule } from '@angular/core';
import { PlatformService } from '../../services/platform.service';
import { CachingInterceptor } from '../../services/caching-interceptor.service';
@NgModule({
imports: [CommonModule, FormsModule],
declarations: [],
exports: [],
entryComponents: [EntryHereComponent]
})
export class StructurModule {
public static forRoot(): ModuleWithProviders {
return { ngModule: StructurModule, providers: [PlatformService,
{
provide: HTTP_INTERCEPTORS,
useExisting: CachingInterceptor,
multi: true
},HttpClient] };
}
}
I don't understand, what are missing so it giving error
No provider for HttpHandler.
If I add HttpHandler in provider in module file, It start giving error for provide: HTTP_INTERCEPTORS, component.
Upvotes: 65
Views: 74130
Reputation: 174
I encountered the same problem when I upgraded my project from Angular v17 to v18.1.4, you just need to include provideHttpClient() in app.config.ts file (code should look like this):
export const appConfig: ApplicationConfig = {
providers: [
provideRouter(routes),
provideHttpClient()
]
};
And please remove HttpClientModule from providers list if you have specified it somewhere as a provider since it is deprecated and can lead to unexpected behavior (my interceptors wouldn't work because of this).
Upvotes: 2
Reputation: 1
For applications without @NgModule,such as Angular 17,HttpClient,HttpHandler can be placed in the provider's array of the component or TestBed.configureTestingModule()
import {HttpClient, HttpHandler} from '@angular/common/http';
For components
@Component({
providers: [HttpClient, HttpHandler]
})
For tests
TestBed.configureTestingModule({
providers: [HttpClient, HttpHandler]
});
Upvotes: 0
Reputation: 318
Add HttpClientModule to your imports[] in app.module.ts. This might be one of the mistakes.
Upvotes: 6
Reputation: 3186
HttpClient
is introduced in angular 4.3,so if you want to use HttpClient
you need to import HttpClientModule
from '@angular/common/http'
. Make sure to import HttpClientModule
after BrowserModule
as shown below. This official doc and so answer will give you indepth information.
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [
BrowserModule,
HttpClientModule
],
...
Upvotes: 184