Skip to content

Commit

Permalink
refactor: Update HttpInterceptor to use HttpInterceptorFn in Angular v17
Browse files Browse the repository at this point in the history
  • Loading branch information
manthanank committed Oct 9, 2024
1 parent cb82a13 commit 7b2df19
Showing 1 changed file with 27 additions and 11 deletions.
38 changes: 27 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3972,21 +3972,37 @@ import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/c
import { Observable } from 'rxjs';

@Injectable()
export class MyInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// Modify the request before it is sent
const modifiedRequest = request.clone({
setHeaders: {
'Authorization': 'Bearer my-token'
}
});

// Pass the modified request to the next handler
return next.handle(modifiedRequest);
export class ErrorInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log('Request started');
return next.handle(req).pipe(
catchError((error) => {
console.error('Request failed', error);
return throwError(error);
})
);
}
}
```

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:

```typescript
import { HttpInterceptorFn } from '@angular/common/http';
import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';

export const ErrorInterceptor: HttpInterceptorFn = (req, next) => {
console.log('Request started');
return next.handle(req).pipe(
catchError((error) => {
console.error('Request failed', error);
return throwError(error);
})
);
};
```

### Using Observable

```typescript
Expand Down

0 comments on commit 7b2df19

Please sign in to comment.