How can we correctly extract a value from the callback of an asynchronous function within another asynchronous function in Angular 6?

I am currently facing an issue with my HTTP provider where I need to access a token value stored in local storage during a GET request. The token value is retrieved using another provider through the getToken function in the HTTP provider. However, I am unable to successfully retrieve the token value in the HTTP call. Can anyone offer guidance on the correct approach to solve this?

Any advice would be greatly appreciated.

this.httpProvider.doGetRequest(Constants.API_SERVER_URL+Constants.API_ENDPOINT_THREADS)
      .subscribe(res => {
        console.log(res);
        this.loading.dismiss();
      }, (error) => {
        console.log(error);
        this.err = error;
        this.loading.dismiss();
        this.presentToast();
      });

HTTP provider class :

@Injectable()
export class HttpProvider {

  constructor(public http: HttpClient,
              public dataProvider: DataProvider,
              public locStor: LocalStorageProvider) {
    console.log('Hello HttpProvider Provider');
  }

  public doGetRequest(url: string) {
    return this.http.get(url, this.getHeaders());
  }

  public doPostRequest(url: string, params: any) {
    return this.http.post(url, params);
  }

  public getHeaders() {
    return {
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'Authorization': 'Bearer test',
        'token': this.getToken()
      },
      params: new HttpParams()
    };
  }

  private getToken() {

    this.locStor.getValue(Constants.LS_KEY_USER_TOKEN).then((val) => {
      return val;
    });

  }
}

Updated version

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import {HttpHeaders} from "@angular/common/http";
import {LocalStorageProvider} from "../local-storage/local-storage";
import {Constants} from "../../app/constants";
import {Headers} from "@angular/http";
import {HttpParams} from "@angular/common/http";
import {DataProvider} from "../data/data";
import 'rxjs/add/observable/fromPromise';
import { Observable } from 'rxjs/Observable';
import {FromObservable} from "rxjs-compat/observable/FromObservable";
import {PromiseObservable} from "rxjs-compat/observable/PromiseObservable";

@Injectable()
export class HttpProvider {

  constructor(public http: HttpClient,
              public dataProvider: DataProvider,
              public locStor: LocalStorageProvider) {
    console.log('Hello HttpProvider Provider');
  }

  public doGetRequest(url: string) {
    //return this.http.get(url);

    return Observable.fromPromise((this.getHeaders()).flatMap((headers) => {
      this.http.get(url, headers);
    }));

  }

  public doPostRequest(url: string, params: any) {
    return this.http.post(url, params);
  }

  public getHeaders() {
    return this.locStor.getValue(Constants.LS_KEY_USER_TOKEN).then((val) => {
      return {
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
          'Authorization': 'Bearer test',
          'token': val
        },
        params: new HttpParams()
      };
    });

  }

  private getToken() {
    this.locStor.getValue(Constants.LS_KEY_USER_TOKEN);
    return '222';
  }
}

Answer №1

If I were to create a similar implementation, it might look something like the following:

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/fromPromise';
import 'rxjs/add/operator/mergeMap'; 

@Injectable()
export class ApiService {

  constructor(public httpClient: HttpClient,
              public dataService: DataService) {
    console.log('Hello ApiService');
  }

  public get(url: string) {
    return Observable.fromPromise(this.generateHeaders()).flatMap((headers) => {
      this.httpClient.get(url, headers);
    });
  }

  public post(url: string, params: any) {
    return this.httpClient.post(url, params);
  }

  private generateHeaders() {
    return this.getToken().then((token) => ({
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer test',
        'token': token,
      }
    }));
  }

  private getToken() {
    return this.dataService.getUserToken();
  }

}

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

Discover information about the client using the node.js net library

I have implemented a nodejs cluster with socket.io, where the master thread uses the net library to listen on a port and pass connections to workers based on the client's IP address. Everything is functioning properly, but I am interested in testing b ...

Validating environment variable values in an AWS CDK TypeScript project

I am facing a problem where I need to include the deployment_env tag with values of either dev, test, or prod on all resources deployed to AWS within a CDK stack. All resources should have identical properties, except for this one tag. I attempted to uti ...

Stop webpack from stripping out the crypto module in the nodejs API

Working on a node-js API within an nx workspace, I encountered a challenge with using the core crypto node-js module. It seems like webpack might be stripping it out. The code snippet causing the issue is: crypto.getRandomValues(new Uint32Array(1))[0].toS ...

Making @types compatible with TypeScript 2.1 in Visual Studio 2015 Update 3

The potential of TS 2.x @types is intriguing, but I'm struggling to make it work effectively! I'm using Visual Studio 2015 - version 14.0.25431.01 Update 3 My TypeScript version for Visual Studio 2015 is 2.1.4, downloaded from this link The VS ...

Optimizing an ASP.NET web application for seamless integration with Angular 2 and TypeScript

For the past couple of days, I have been delving into angular2. I am curious to understand the process of configuring my project to effectively utilize angular2 and typescript. My development environment is Visual Studio 2015. Can you guide me on the nec ...

The React function is encountering a situation where the action payload is not

I encountered an error stating Cannot read property 'data' of undefined switch (action.type){ case REGISTER_USER: console.log("Action ", action);// This prints {type: "REGISTER_USER", payload: undefined} return [action.payload.data, ...

Challenges with importing class-based decorators in Vue using Typescript

Currently, I am in the process of setting up Vue 3 with TypeScript and utilizing class-based components. Unfortunately, I have encountered an issue while attempting to import the Component decorator within the Vue constructor: An error message appears sta ...

Setting default parameters for TypeScript generics

Let's say I define a function like this: const myFunc = <T, > (data: T) => { return data?.map((d) => ({name: d.name}) } The TypeScript compiler throws an error saying: Property 'name' does not exist on type 'T', whic ...

Troubles with Declaration Merging in Angular 2 Implementation

I'm currently working on incorporating a custom RxJS operator into my project, following the steps outlined in this particular answer. Below are the relevant code snippets from my application: rxjs-extensions.ts import { Observable } from 'rxjs ...

Can you explain the distinctions when it comes to sending constants as Props in Angular?

During my experience with the dx-calendar component from DevExtreme, I encountered an issue. I was attempting to set Monday as the first day of the week by passing 1 to the firstDayOfWeek property. Initially, I tried: <dx-calendar firstDayOfWeek="1 ...

Utilizing the polymer paper-dialog component in an Angular 2 TypeScript application

I have imported the paper-dialog from bower, but I am facing an issue with showing the dialog using the open() method. app.component.html <paper-icon-button icon="social:person-outline" data-dialog="dialog" id="sing_in_dialog" (click)="clickHandler()" ...

Issue: The variable 'HelloWorld' has been declared but not utilized

Why am I encountering an error when using TypeScript, Composition API, and Pug templating together in Vue 3? How do I resolve this issue when importing a component with the Composition API and using it in a Pug template? ...

Error message in Visual Studio 2017: Identical name 'URLs' declared twice in

In our Visual Studio 2017 project, we have multiple TypeScript files that define a URLs class. Each file contains different implementations of the class to change site URLs based on the specific use case: customer/urls.ts namespace Portal { export cl ...

Exploring the depths of a TypeScript interface with unknown levels of complexity

My current challenge involves a recursive function that operates on an object with a generic interface. This function essentially traverses the object and creates a new one with a nearly identical interface, except for the leaf nodes which are transformed ...

The TypeScript library React-Time-Ago seems to require a number, but I'm passing it a string instead. I'm struggling to find a way to make it accept a number

import ReactTimeAgo from "react-time-ago" <ReactTimeAgo date = {tweet._createdAt} /> _createdAt displays time in the format 2022-06-02T01:16:40Z To convert this into a more human-readable form like " ...

Transforming Angular Material Components into TypeScript

As I continue to learn AngularJS, I have been following tutorials mainly in TypeScript. Now that I want to incorporate Angular Materials into my app, I've found that the component I need is written in JS. You can find the component at https://materia ...

Is there a method in RXJS that allows an operator to pause and wait for a subscription to finish before proceeding with the workflow?

Being new to the world of RXJS, I have spent a considerable amount of time researching and seeking solutions on stackoverflow and various documentation sources before turning to ask for help here. However, despite my efforts, I am struggling to make my log ...

TSLint has detected an error: the name 'Observable' has been shadowed

When I run tslint, I am encountering an error that was not present before. It reads as follows: ERROR: C:/...path..to../observable-debug-operator.ts[27, 13]: Shadowed name: 'Observable' I recently implemented a debug operator to my Observable b ...

Can I modify Visual Studio Code settings using my own custom extension?

I am in the process of creating a new vscode extension and I'm looking to include some specific values in the "file.associations" section of the settings file once the user installs my extension. Is this something that can be achieved? I've look ...

Step-by-step guide on dynamically setting a value in a select option using Angular

Here is a select option that I have: <div class="input-field col width"> <select name="GENDER" class="genderSelect" ng-model="view.activeResource.ValueType" ngModel> <option value="" disabled selected>Choose your option</option& ...