Executing an asynchronous function within an Angular 7 interceptor is crucial

I've been working on creating an interceptor to handle a situation where a function needs to be called to refresh the session upon receiving a 401 error response. Here's what I have so far but I'm facing build issues and struggling to figure out how to make it work:

intercept(
request: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
request = request.clone({
  withCredentials: true
});
return next.handle(request).pipe(
  catchError((error: HttpErrorResponse) => {
    if (error.status === 401) {
      return this.userAPI
        .refreshSession(this.authService.getRefreshToken())
        .then(res => {
          this.authService.setAuthenticated(false);
          return next.handle(request);
        });
    } else {
      this.authService.setAuthenticated(false);
    }
  })
 );
}

VS Code is showing this error message:

Type 'Observable<HttpSentEvent | HttpHeaderResponse | HttpProgressEvent | HttpResponse<any> | HttpUserEvent<any> | Observable<HttpEvent<any>>' is not assignable to type 'Observable<HttpEvent<any>>'.

Answer №1

catchError is required to result in an observable. You could try the following solution or something along those lines:

intercept(
request: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
request = request.clone({
  withCredentials: true
});
return next.handle(request).pipe(
  catchError((error: HttpErrorResponse) => {
    if (error.status === 401) {
      return this.userAPI
        .refreshSession(this.authService.getRefreshToken())
        .then(res => {
          this.authService.setAuthenticated(false);
          return next.handle(request);
        });
    } else {
      this.authService.setAuthenticated(false);
      // Include this
      return next.handle(request);
    }
  })
 );
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for preventing keyboard events from being inherited by all pages in the stack in Ionic framework

In my Ionic 3 app, I have a specific page called Page1 that requires customized keyboard handling. Here is how I implemented it on Page1: @Component({ ... host: { '(document:keydown)': 'handleKeyboardEvents($event)' } }) expo ...

When using Angular 2 formControl, manually changing the value may not be detected by the form

Having a simple form (as shown below), I am encountering an issue: Manually entering input value causes form.controls['myValue'].value to change If #myInput value is changed programmatically, the form completely ignores that change What could ...

Once app.component's ngOnInit is completed, the child's ngOnInit will be triggered in Angular6

I am working on a project where I need to make an API call in the app.component's initialization process. The child component should then wait for the completion of the app.component's ngOnInit() before proceeding. In app.component.ts: ngOnInit ...

Typescript error: Cannot assign type to argument

Exploring the world of typescript (2.5.2) and looking for clarity on why the first call works but the second one encounters an error: function printPerson(person: {firstName: string; lastName: string}): void{ console.log(person.firstName + " " + per ...

What is the process for unit testing the 'navigate' function in Angular that includes query parameters?

Below is the code snippet from my component: editThis(id) { this.router.navigate(['/categories/edit'], { queryParams: { id: id } }); } The following represents my unit test-case: fit('should call navigate with correct parameters&ap ...

Angular tips: Retrieving user ID for API authorization

Within the authorize.service.ts file, there is a service code block that allows me to retrieve the current logged in user's userName: public getUser(): Observable<IUser | null> { return concat( this.userSubject.pipe(take(1), filter( ...

Enhance your Angular2+ writing skills by delving into the intricacies of subscriptions with `

Seeking assistance to enhance the code structure. I am struggling with understanding switchMap, mergeMap and how to avoid nested subscriptions. this.service .service1('something') .pipe(takeUntil(this.unsubscribe)) .subscribe( (s1result ...

Using Conditional Types in Supabase Query results in the TypeScript error, "Type is incompatible with type 'never'."

Query I have encountered a TypeScript issue while working on a Next.js project with Supabase as the backend. To handle responses from Supabase queries, I created some helper types, but I'm stuck on resolving this problem. Helper Types Overview: Belo ...

implement some level of control within the ngFor directive in Angular

For instance, let's say I have an ngfor loop: <ng-container *ngFor="let setting of settings | trackBy: trackById"> <button mat-button [matMenuTriggerFor]="menu">Menu</button> <mat-me ...

Guide on troubleshooting Node TypeScript in Visual Studio Code when the JavaScript source is stored in a separate directory

When using Visual Studio Code, I am able to debug and step through the TypeScript source code of Main.ts. This is possible as long as the JavaScript and map files are located in the same folder as the TypeScript source. This setup works well in this struc ...

Obtaining a binary value in the switch component of materialize framework with Typescript

Is there a way in Typescript to assign a value of 1 when a checkbox is checked and 0 otherwise? I am working on a project that uses the materialize framework. Below is the code snippet in question: <div class='switch'> <label&g ...

defining data types based on specific conditions within an object {typescript}

Can someone help with implementing conditional function typing in an object? let obj = { function myfunc (input: string): number; function myfunc (input: number): string; myfunc: function (input: string|number):string|number { ... } } I've been ...

Vue.js with TypeScript: The property 'xxx' is not found on the type 'never'

I have a computed method that I am trying to execute: get dronesFiltered(){ const filtered = this.drones.filter((drone) => { return drone.id.toString().indexOf(this.filterId) > -1 && drone.name.toLowerCase().toString().in ...

Learn how to define an array of member names in TypeScript for a specific type

Is there a way to generate an array containing the names of members of a specific type in an expression? For example: export type FileInfo = { id: number title ?: string ext?: string|null } const fileinfo_fields = ["id","ext&qu ...

Is it possible to replicate a type in TypeScript using echo?

Is there any equivalent in TypeScript to the following code snippet? type TypeA = { x: number }; printType(TypeA); I have found a method that consistently enables TypeScript to provide a type description. const y = { x: 1, z: 'hello', }; ...

Trouble with @Input() in Angular 2 when selector is surrounded by HTML tag

In my Angular2 project, I have a component named TabTitleComponent. import { Component, OnInit,Input,AfterViewInit } from '@angular/core'; @Component({ selector: 'tab-title', templateUrl: './tab-title.component.html', ...

Maintaining checkbox selection while switching pages in Angular

When I try to edit the settings for accepting payments in all currencies under the "Pricing" component, the checkbox is unchecked every time I return to the "General" section. How can I prevent this from happening and keep the checkbox checked? Refer to ...

VS Code is flagging TypeScript errors following the recent software update

After updating my VS Code, I started seeing TypeScript error messages like the following: ButtonUnstyled.types.d.ts: Module '"/components/node_modules/@types/react/index"' can only be default-imported using the 'esModuleInterop&a ...

Utilizing CSS classes to style custom day templates in ng-bootstraps datepicker

Currently, I am utilizing ng-bootstraps datepicker to showcase user data on a daily basis. I have implemented a custom day template to apply specific CSS classes. <ng-template #customDay let-date> <div class="custom-day" [ngCla ...

Searching for a working node within a document (encountering a throw err) in the context of Express and Node

Seeking a solution: I'm fairly new to node and express. When I attempt to run my server.js file, I encounter an error right away. https://i.sstatic.net/EdF5N.png The error message claims that I am on the incorrect path, but I believe otherwise. Ref ...