How can I make TypeScript's http.get Observable wait for the inline parameter to be returned?

I'm currently facing an issue with my http.get call in which I need one of the parameters (getUserToken) to be returned before the function is executed. However, I don't want to chain them together since the calling function getSomeData returns an observable that is utilized by many other functions.

The problem lies in getSomeData as it requires getUserToken to be returned, but getUserToken always ends up being null due to improper handling of promises. I'm struggling to find a solution for this dilemma.

This function initiates the call and is used by multiple functions. I'm hesitant to make any changes here.

displayData(){
 let mySubscription = this.getSomeData();
    mySubscription.subscribe(retJson => {
      if (retJson != null && retJson !== undefined){
        console.log(retJson);
      }
    });
}

The issue arises when trying to return the http.get call due to the dependency on getUserToken.

getSomeData(){
     let temporary = this.http.get(serviceUrl, getUserToken() ).map((response: Response) => {
       return response;
  });
return temporary;
}

The challenge lies in getUserToken making its own server call. Is there a way to encapsulate this within an observable or promise that can be resolved inline with the http.get inside the getSomeData function?

getUserToken(){
     this.authenticationService.getToken()
            .subscribe(responseData => {
              if (responseData){
                let headers = new Headers({ 'Authorization': 'Bearer ' + responseData.token });
                return new RequestOptions({ headers: headers });
              }
            });
}


Answer №1

To achieve this functionality, you can utilize the `switchMap` operator.

@Injectable()
class SomeClass {
   // Constructor code is excluded

   public displayData():void {
      const subscription:Subscription = this.getSomeData()
         .filter(retJson => !!retJson) // Filter only if JSON is truthy
         .subscribe(console.log);
   }

   private getSomeData():Observable<any /*Replace with correct data type*/ > {
      return this.getUserToken()
         .switchMap(userToken =>
            this.http.get(serviceUrl,
               new RequestOptions({headers: new Headers({...userToken)})
            )
         );
   }

   private getUserToken():Observable<{authorization: string}> {
      return this.authenticationService.getToken()
        .filter(responseData => !!responseData)
        .map(responseData => ({'Authorization': `Bearer ${responseData.token}`}));
   }

}

Alternatively, for clarity in the stream, you could condense it into a single method like this (not recommended, but for illustrative purposes):

const subscription:Subscription = this.authenticationService.getToken()
   .filter(responseData => !!responseData)
   .switchMap(userToken =>
        this.http.get(serviceUrl,
           new RequestOptions({headers: new Headers({'Authorization': `Bearer ${responseData.token}`})})
        )
    )
    .filter(retJson => !!retJson)
    .subscribe(console.log);

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

Guide on linking action observables to emit values in sync before emitting a final value

If you're familiar with Redux-Observable, I have a method that accepts an observable as input and returns another observable with the following type signature: function (action$: Observable<Action>): Observable<Action>; When this method r ...

"Encountering a Bug in Angular 2 Related to Chart.js

I am currently in the process of developing a Twitter-style application using a Typescript/Angular2 front-end framework and a Node.js back-end. The foundation of my project is derived from Levi Botelho's Angular 2 Projects video tutorial, although I h ...

An issue occurred in the modal window following the relocation of project files

I encountered an issue with the modal in my Nativescript project after rearranging a few project files, including the modal. I updated the imports and deleted any compiled JavaScript files to ensure that my project could recompile correctly. Although I&ap ...

Can you explain the significance of tslint's message: "Warning: The 'no-use-before-declare' rule necessitates type information"?

Can someone explain the significance of tslint's "no-use-before-declare" rule warning, which states that it requires type information? I've tried researching online but still don't fully understand its implications. ...

Combine and modify an object coming from a different component

Recently, I developed a customized viewer component specifically designed to showcase song sheets. One of my main objectives is to give users the ability to adjust font settings and other display preferences at their discretion. In order to accomplish this ...

Why hasn't the variable been defined?

Why am I receiving an error message saying "test is not defined" in this code? Even though I have properly defined the variable in another service file, it seems to be causing issues here. Any insights on what could be going wrong? import { Injectable } f ...

In TypeScript, encountering an unanticipated intersection

In my "models" registry, whenever I select a model and invoke a method on it, TypeScript anticipates an intersection of parameters across all registered models. To demonstrate this issue concisely, I've created a dummy method called "getName". expor ...

Error message: "Uncaught TypeError in NextJS caused by issues with UseStates and Array

For quite some time now, I've been facing an issue while attempting to map an array in my NextJS project. The particular error that keeps popping up is: ⨯ src\app\delivery\cart\page.tsx (30:9) @ map ⨯ TypeError: Cannot read pr ...

Exploring Geofirestore's capabilities with advanced query functionalities

Thinking about updating my firestore collection structure to incorporate geoquery in my app. Geofirestore requires a specific structure: interface GeoDocument { g: string; l: GeoPoint; d: DocumentData; } I understand that geofirestore does ...

Tips for embedding HTML/CSS snippets in backticks when using TypeScript with AngularJS

Does anyone else experience the issue of their Angular 2 templates showing up as gray text in Visual Studio Code? I'm unable to use autocomplete or see my CSS properly. Is this a settings problem or is there a plugin that can solve this? BTW, I am us ...

Sass Alert: The mixin called roboto-family is missing from the stylesheet. Trace: Problem detected in src/pages/forms/forms.scss at

Greetings, I am diving into the world of Ionic for the first time. Recently, I embarked on a new project in Ionic and decided to integrate a theme. To do so, I copied an .html file, an .scss file, and also created a .ts file. Forms.html <!DOCTYPE html ...

Generating TypeScript declarations for legacy CommonJS dependencies with the correct "module" setting

One of my challenges involves creating type declarations for outdated dependencies that produce CJS modules and lack typings. An example is the aabb-3d module (although this issue isn't specific to that particular module). To generate the declaration ...

Replacing URLs in Typescript using Ionic 3 and Angular

Currently facing some difficulties getting this simple task to work... Here is the URL format I am dealing with: https://website.com/image{width}x{height}.jpg My objective is to replace the {width} and {height} placeholders. I attempted using this func ...

What is the best way to inform the user of their login status in Angular?

As a newcomer to angularfire2, I am currently working on implementing authentication and providing the user with feedback on their login status. I am using version angularfire2": "^5.0.0-rc.4. I came across an example on this site, but I am unsure of how i ...

Navigating through async functions in an Express.js router

Encountered a lint error indicating that Promises cannot be returned in places where a void is expected. Both functions [validateJWT, getUser] are async functions. Any suggestions on how to resolve this issue without compromising the linter guidelines by u ...

Setting up ReactJS and TypeScript in a fresh MVC5 project from scratch

After extensively trying out various tutorials, I have yet to successfully run a basic MVC5 project using TypeScript and ReactJS. For reference, I have created these projects from scratch in Visual Studio 2015 with .NET 4.6.1, using the ASP.NET Web Applic ...

What is the best way to implement a condition within an ngFor loop in Angular?

I am looking to iterate the user list with a condition. <li *ngFor="let user of users" *ngIf="user.age>25"> {{user.name}} </li> I understand that this code is incorrect. However, I would like to achieve something similar. Is there any way ...

An error encountered while trying to utilize the npm convert-units package within an Ionic 4 application

In my Ionic 4 app, I am utilizing version 2.3.4 of the npm package called convert-units. To install this package in my Ionic 4 application, I used the CLI command: npm i convert-units --save However, upon importing the library with import { convert } fro ...

Error when attempting to add data into MongoDB using Node.JS: "The type 'string' cannot be assigned to type 'ObjectId | undefined'."

Attempting to add a document to the collection results in an error when specifying the _id field of the added document. How can I insert a document with an _id that is not an ObjectId? The error occurs with the following code. Omitting the _id resolves th ...

Develop a FormGroup through the implementation of a reusable component structure

I am in need of creating multiple FormGroups with the same definition. To achieve this, I have set up a constant variable with the following structure: export const predefinedFormGroup = { 'field1': new FormControl(null, [Validators.required]) ...