Retrieve the value of a promise and transfer it to the subsequent function of an observable

For my Angular 9 application, I have created a custom interceptor called AuthorizationHeaderInterceptor:

@Injectable()
export class AuthorizationHeaderInterceptor implements HttpInterceptor {

  constructor(private authenticationService: AuthenticationService) { }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    return from(this.authenticationService.getAuthenticationHeader()).pipe(header => {

      request = request.clone({
        setHeaders: { 
          Authorization: `${header}`
        }
      });

      return next.handle(request);

    });

  }

}

The method

authenticationService.getAuthenticationHeader()
retrieves a header value as a Promise<string>, which is then added to the request.

To convert the Promise into an Observable, I utilize from and pipe on the resulting Observable.

Question: Is it necessary to include map after applying pipe? And furthermore, is this the correct approach for implementing this interceptor?

Answer №1

If you are returning an observable, the most suitable operator to use would be switchMap.

@Injectable()
export class AuthorizationHeaderInterceptor implements HttpInterceptor {
  constructor(private authenticationService: AuthenticationService) { }
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return from(this.authenticationService.getAuthenticationHeader()).pipe(
      switchMap(header => {         // <-- consider using `switchMap` here
        request = request.clone({
          setHeaders: { 
            Authorization: `${header}`
          }
        });
        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

The attribute 'y' is not found within the data type 'number'

Currently working on a project using Vue.js, Quasar, and TypeScript. However, encountering errors that state the following: Property 'y' does not exist on type 'number | { x: number[]; y: number[]; }'. Property 'y' does not ...

Tips for addressing style issues within innerText

I am trying to use PrismJS to highlight HTML code, but the inner text function doesn't recognize line breaks (\n). <pre class="language-markup background-code"><code [innerText]="getHtmlCode()""></code> I have been working wi ...

What is the best way to showcase the Observable information I receive from calling my api with Angular?

Just beginning my journey with Angular, I am on a quest to create a simple app that showcases a catalog of products. In my TypeScript file, I have a getProducts() function that calls an API and returns an observable list of products consisting of attribute ...

The srcSet functionality in the Image component seems to be malfunctioning in the next.js framework, as it is failing to display

Check out my Next.js code snippet below: import React from "react"; import style from "@/styles/Home.module.css"; import Image from "next/image"; function index() { return ( <> <div className="contai ...

Tips for sending a value to a container component

Within my task management application, I have implemented two selectors: export const selectFilter = (state: RootState) => state.visibilityFilter export const selectVisibleTodos = createSelector( [selectTodos, selectFilter], (todos: Todo[], filter : ...

Bringing Typescript functions into the current module's scope

Is it possible to import and reference a module (a collection of functions) in typescript without the need for the Module. prefix? For instance: import * as Operations from './Operations'; Can I access Operations.example() simply as example()? ...

Attempting to retrieve JSON data using the subscribe method in Angular version 7.x

In my Angular 7.x application, I have a component that calls a function from a service. This function makes a GET request to a backend endpoint and retrieves an array of users. Although I can view the data within the subscribe method (where console.log is ...

Enhance the capabilities of a basic object by incorporating a superclass through the creation of

I'm currently developing a library using Typescript 2.0 that can be utilized from both Typescript and JavaScript. Within the library, there is a class called Component and a function named registerComponent, both written in Typescript. My goal is to ...

Encountering error code TS1003 while trying to access object properties using bracket notation in Typescript

How can object property be referenced using bracket notation in TypeScript? In traditional JavaScript, it can be done like this: getValue(object, key) { return object[key]; } By calling getValue({someKey: 1}, "someKey"), the function will return 1. H ...

When the appdir is utilized, the subsequent export process encounters a failure with the error message "PageNotFoundError: Module for page /(...) not

I have implemented NextJS with the experimental appDir flag and organized my pages in the following manner: https://i.stack.imgur.com/M7r0k.png My layout.tsx file at the root and onboard look like this: export default function DefaultLayout({ children }) ...

Detecting changes in Angular custom form controls when using `mat-select` with the `selectionChange` event

I'm facing an issue with my custom form control that includes a mat-select element I've been attempting to listen for the change event in the parent component However, my onTouchedCallback doesn't seem to be functioning for some reason Wh ...

Experiencing an issue with mui/material grid causing errors

An error occurred in the file Grid2.js within node_modules/@mui/material/Unstable_Grid2. The export 'createGrid' (imported as 'createGrid2') could not be found in '@mui/system/Unstable_Grid' as the module has no exports. Desp ...

Unable to call a component's method from a different component in Angular 7

How can I call the toggleSidebar() method of the SidebarComponent from the HeaderComponent using the callToggleSidebarOnToggleSidebarBtn() method? I am encountering an error that I cannot comprehend. What is the correct way to use a method of one component ...

Challenges with incorporating asynchronously fetched data in component operations

I have encountered an issue where the data retrieved from a server in a service is available in the component's template but not in the actual code. This seems strange to me. I made the call in the ngOnInit method of my main AppComponent ngOnInit() { ...

What is the best way to have text wrap around an icon in my React application?

I am facing an issue while trying to display the note description over the trash icon in a React app. I have tried various methods but can't seem to achieve the desired effect. Can anyone guide me on how to get this layout? Here is what I intend to a ...

What could be causing the data-* prefix to malfunction in Angular 9?

I'm facing an issue with a basic component in Angular 9. Check out the code below: Component : @Component({ selector: 'hello', template: `<h1>Hello {{name}}!</h1>`, styles: [`h1 { font-family: Lato; }`] }) export class He ...

receiving feedback from Firebase push action

I have a method to add a new entry in Firebase Realtime Database like so: assignGiftCard(email:string, type: string, value: number, code:string){ let giftCard = { "type" : type, "value": value, "code": code } this.db.list(& ...

How can I make my webpage fill the entire width of an iPhone screen when in landscape mode using Angular or React?

While testing my website on my iPhone, I noticed a significant gap appearing on either side of the app in landscape view in Safari. Is there a solution to fix this issue? The problem occurs in both Angular and React applications, examples of which are disp ...

Check for the data attributes of MenuItem in the TextField's onChange event listener

Currently, I am facing a situation where I have a TextField in select mode with several MenuItems. My goal is to pass additional data while handling the TextField's onChange event. I had the idea of using data attributes on the MenuItems for this pur ...

Conditional Rendering with Next.js for Smaller Displays

I've implemented a custom hook to dynamically render different elements on the webpage depending on the screen size. However, I've noticed that there is a slight delay during rendering due to the useEffect hook. The conditionally rendered element ...