Skip to content

Commit 7b2df19

Browse files
committed
refactor: Update HttpInterceptor to use HttpInterceptorFn in Angular v17
1 parent cb82a13 commit 7b2df19

File tree

1 file changed

+27
-11
lines changed

1 file changed

+27
-11
lines changed

Diff for: README.md

+27-11
Original file line numberDiff line numberDiff line change
@@ -3972,21 +3972,37 @@ import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/c
39723972
import { Observable } from 'rxjs';
39733973

39743974
@Injectable()
3975-
export class MyInterceptor implements HttpInterceptor {
3976-
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
3977-
// Modify the request before it is sent
3978-
const modifiedRequest = request.clone({
3979-
setHeaders: {
3980-
'Authorization': 'Bearer my-token'
3981-
}
3982-
});
3983-
3984-
// Pass the modified request to the next handler
3985-
return next.handle(modifiedRequest);
3975+
export class ErrorInterceptor implements HttpInterceptor {
3976+
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
3977+
console.log('Request started');
3978+
return next.handle(req).pipe(
3979+
catchError((error) => {
3980+
console.error('Request failed', error);
3981+
return throwError(error);
3982+
})
3983+
);
39863984
}
39873985
}
39883986
```
39893987

3988+
In angular v17, the `HttpInterceptor` interface has been deprecated in favor of the `HttpInterceptorFn` type. The `HttpInterceptorFn` type is a function that takes a `HttpRequest` and a `HttpHandler` and returns an `Observable<HttpEvent>`. Here is an example of how to create an interceptor using the `HttpInterceptorFn` type:
3989+
3990+
```typescript
3991+
import { HttpInterceptorFn } from '@angular/common/http';
3992+
import { catchError } from 'rxjs/operators';
3993+
import { throwError } from 'rxjs';
3994+
3995+
export const ErrorInterceptor: HttpInterceptorFn = (req, next) => {
3996+
console.log('Request started');
3997+
return next.handle(req).pipe(
3998+
catchError((error) => {
3999+
console.error('Request failed', error);
4000+
return throwError(error);
4001+
})
4002+
);
4003+
};
4004+
```
4005+
39904006
### Using Observable
39914007

39924008
```typescript

0 commit comments

Comments
 (0)