I'm working on implementing multiple interceptors in my Angular7 project for tasks like authentication and error handling. However, I feel like I might be overlooking something simple and would appreciate a fresh set of eyes to help me spot any mistakes.
One key thing I know I need is the new HttpClientModule for Angular7.
In my app.module.ts file:
import { HttpClientModule } from '@angular/common/http';
imports: [
BrowserModule,
AppRoutingModule,
FormsModule,
HttpClientModule
],
providers: [
AuthService,
ErrorInterceptor
],
Here is my errorInterceptor.ts code:
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('Oops! An error occurred:', error);
}));
}
}
And here is my my.service.ts code:
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('Testing service', response);
})).subscribe();
}
}
If you require more code or information, please let me know. Any assistance will be greatly appreciated!