Reputation: 93
I am planning on using a couple of different interceptors for several things; auth, error handling, etc. I'm sure I'm just missing something obvious, so I'd love to get some extra eyes on it to help me find my mistake.
I'm using Angular7 and I know that I need to use the new HttpClientModule.
app.module.ts:
import { HttpClientModule } from '@angular/common/http';
imports: [
BrowserModule,
AppRoutingModule,
FormsModule,
HttpClientModule
],
providers: [
AuthService,
ErrorInterceptor],
errorInterceptor.ts:
import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
constructor() { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).pipe(catchError(err => {
const error = err.error.message || err.statusText;
return throwError('yo you got an error =>', error);
}));
}
}
my.service.ts:
import { Injectable } from '@angular/core';
import { map} from 'rxjs/operators';
import {HttpClient} from "@angular/common/http";
@Injectable({
providedIn: 'root'
})
export class MyService {
constructor(private http: HttpClient) {
}
getSomeData() {
this.http.post<any>(`https://getsomedata.com/youneedthisdata`, {})
.pipe(map(response => {
console.log('test service', response);
})).subscribe();
}
}
Let me know if you need any other code. Any help is much appreciated!
Upvotes: 0
Views: 151
Reputation: 4821
The issue is that you need special syntax to provide the interceptor.
{ provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true }
needs to go under your providers array in place of what you currently have for ErrorInterceptor.
Upvotes: 1