Dealing with requests on an interceptor after receiving a value from an observable in RxJS and Angular: Tips and tricks

Coming from a background in AngularJS while learning Angular 5, observables are still causing some confusion for me.

I'm currently working on writing an HTTP interceptor for my authentication service. However, I'm struggling to properly return the next.handle(req) method after retrieving a value from the localstorage service (or any observable for that matter). I'm unsure of how to handle this using the subscribe method.

Below is the code I have at the moment (which is not functioning as expected):

@Injectable()
export class AuthinterceptorService implements HttpInterceptor {

  constructor(private storage: LocalStorage) { }

  intercept(req: HttpRequest<any>, next: HttpHandler):Observable<HttpEvent<any>> {
    return this.storage.getItem('authToken').subscribe(res => {
      return next.handle(req);
    });
  }    

}

As you can see, I'm struggling with simply returning the Observable object within my asynchronous call without manipulating the data.

Thank you in advance for your assistance.

Answer №1

If you try to return an Observable within the subscribe method, it will not have any effect. Instead, you should merge it into the chain of operations. You can achieve this by following a structure similar to the one shown below:

return this.storage.getItem('authToken')
  .mergeMap(res => next.handle(req));

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

Utilize a personalized useFetch hook in React.js to transmit a POST request and obtain a response

I recently came across a great resource on this website that provided the logic for a useFetch hook. My goal is simple - I want to send a post request and then map the response into a specific type. While this seems like it should be straightforward, I&apo ...

Issues with the angular datatable causing data not to bind correctly when retrieved from the API

My Angular datatable is not binding properly with the data retrieved from the API. Below is the code I am using: App.component.html <table datatable [dtOptions]="dtOptions" class="row-border hover"> <thead> <tr> ...

What is the best way to condense this code snippet into just a single line?

I am currently working with an array of objects and my main objective is to eliminate duplicates. I have implemented a dictionary as a "filter" mechanism but I am struggling to find alternative ways to refactor this process. I am aware that there must be a ...

The default values for CSS filters

I have a keen interest in various CSS filters: blur brightness contrast grayscale hue-rotate invert opacity saturate sepia Could someone provide the default values for each filter (preferably as a % value, where applicable)? The MDN documentation does no ...

The integration of Angular and Node API within the IISNode directory structure is experiencing functionality issues

Read more about the question I have successfully set up my Node API and Angular component with IISnode. However, when accessing the application from the IIS server, I noticed that they are showing in different directories (see image below). Additionally, I ...

Updating an array directly in the UI without using a proper pipe is against protocol

During my exploration of Pipe functions in Angular, I discovered something interesting. It seems that for non-primitive data types like arrays, any changes made to the elements within the array do not trigger the pipe function to reapply to the updated arr ...

Using Angular and Angular Material to project content within MatDialog.open()

Suppose I have a Component: @Component( selector: "demo-comp", template: ` <div> Some text... <ng-content></ng-content> </div> ` ) export class DemoComponent { constructor(public dialogRef: MatD ...

Unable to access data from the Array by passing the index as an argument to the method

Having trouble retrieving an item from an Array using method() with an index argument that returns undefined export class DataService { public list = [ { id: 11, name: 'Mr. Nice' }, { id: 12, name: 'Narco' }, ...

Discover and showcase individual product information using Product ID in Angular 8 with Firebase integration

I've been struggling to retrieve a single product record from Firebase using Angular 8. I'm new to this and have spent the past two days trying to figure it out. Below is my Firebase database. I have all products displayed on one page, and when c ...

Manipulating a DOM element in Angular 2 to alter its class attribute

I am a beginner in angular2. Here is my code: import { Component, OnInit } from '@angular/core'; @Component({ selector: 'main', template: ` <div class="current"> </div> ` }) export class MainComponent impl ...

Staying patient while the array loads data from Firebase so that methods can be called efficiently

As an Angular newbie, I am working on a project that involves accessing data from Firebase using an Angular service. My goal is to retrieve this data, store it in an array, and then perform some operations on that array. However, due to my limited experien ...

Unable to access file: EACCES: permission denied when trying to open '/Users/emilio/.ionic/daemon.log' - Error occurred due to lack of permissions

Hello everyone in the Ionic community! I've been working on an Ionic v3 project and everything was running smoothly. However, when I attempted to integrate the Geolocation module from @ionic-native/geolocation, I encountered an error message stating: ...

Typescript is issuing warnings when displaying errors for the RTK query

I am currently using React Ts and Rtk query. My goal is to display the API response error on the UI. While it's working, I am encountering a warning that prompts me to set an error type for the response errors. How can I incorporate an error type for ...

AInspector WCAG evaluation found that mat-select does not meet level A compliance standards

As I work on making my website WCAG level A compliant, I've encountered an issue with the mat-select component in Angular material. After running checks with the AInspector extension for Firefox, it appears that the mat-select component lacks aria-con ...

A guide on iterating through a JSON object fetched using Http in Angular 2/Typescript

I am attempting to extract specific data from my JSON file using http. The structure of the JSON is as follows: [{"name":"Name1","perc":33},{"name":"Name2","perc":22},{"name":"Name3","perc":41}] To loop through this retrieved object, I use the following ...

Express and Angular 5 service worker facing compatibility issues

For the past couple of days, I've been struggling with my Angular5 service worker. However, after some investigation, I believe the issue lies in the way I am serving the application. If you're interested in the detailed journey leading up to thi ...

Tips for defining the type of any children property in Typescript

Currently, I am delving into Typescript in conjunction with React where I have a Team Page and a slider component. The slider component is functioning smoothly; however, my goal is to specify the type of children for it. The TeamPage import react, { Fragm ...

Enums are not recognized by TypeScript when used within an array

I have defined an enum as follows: export enum Roles { ADMIN, NONE; } An object is being used which utilizes this enum. The structure of the object is: export interface User { name: string; roles: Roles[]; } Upon fetching this object via a web r ...

Inheritance of Generic Types in TypeScript

Could someone assist me in understanding what is incorrect with the code snippet provided here? I am still learning Typescript. interface ICalcValue { readonly IsNumber: boolean; readonly IsString: boolean; } interface ICalcValue<T> ex ...

What's the best way to declare a component that is intended to be used across all pages of my application?

I have a HeroLogoComponent that is included in the header of every page in my app. It is declared in the app.module like this: @NgModule({ declarations: [ MyApp, HeroLogoComponent, ], ... Based on what I have read in the Angular documentation, usin ...