Angular Pause until the variable is ready

I am in the process of developing a new web application service. The first step involves obtaining a token through the rest API. Once this token is obtained, it needs to be sent as a header to retrieve additional information.

The issue I'm facing is that the function to fetch more information is being triggered before the token variable is properly set (resulting in an empty header). However, if I manually set the token, everything works correctly.

Is there a way to ensure that my function waits until the variable has been assigned a value?

Thank you

gettoken(): void {
this.http.get<InitResponse>('URL' + '/token').subscribe(data => {
    this.token = data.token;
    localStorage.setItem('token', data.token);
    getmoreInfo();
  },
  (err: HttpErrorResponse) => {
    if (err.error instanceof Error) {
      console.log('Client-side error occured.');
    } else {
      console.log('Server-side error occured.');
    }
  }
);

}

Answer №2

The following is my implementationToken method :

  implementationToken(idKey: string): Observable<boolean> {
    let urlAPIKey: string = urlAPIToken;

    urlAPIKey += '/token?id_key=' + idKey;
    let response = encodeURIComponent(urlAPIKey);   

    return this.http.get(urlAPIKey, { withCredentials: true }).pipe(
      map(result => {    
        let key = result.toString();
        localStorage.setItem('key', key);
        return true;
      }));
  }

Furthermore, to facilitate transmission in all HTTP requests, I have an interceptor that automatically includes the token:

const key = localStorage.getItem(KEY_NAME);

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

For more details, please visit: here

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

Node.js server only supports cross-origin requests for protocol schemes when working with an Angular front end

Struggling to configure CORS on a local site hosting a Node.js server and an Angular client. Encountering the following error: Access to XMLHttpRequest at 'localhost:3000/api/v1/users' from origin 'http://localhost:4200' has been bl ...

The Typescript object may be null even with its initial value set

1: let a: Record<string, any> | null = {}; 2: a['b'] = 2; Encountered the TS2531: Object is possibly 'null' error on Row 2 despite having an initial value. To address this issue, the code was updated as follows: 1: let a: Record ...

Having trouble resolving an error while attempting to incorporate an npm module into a vanilla JavaScript application

I admit my lack of expertise in building modern JavaScript apps is becoming evident. Currently, we have a Capacitor app that uses plain JavaScript without any build tools, and it functions well. Our goal is to incorporate Microsoft Code Push support throu ...

encase a function with javascript

let myString = "I am creating a program."; //function to calculate number of letters const letterCount = (str) => str.length; //function to calculate number of words const wordCount = (str) => str.split(" ").length; //function ...

Unlocking hidden gridview column values with the power of jQuery

Within my gridview control, there are 4 columns, with one column being invisible which contains the Email Address information. <asp:GridView id='gridData' runat='server'> <Columns> <asp:TemplateField> ...

User events in the fullCalendar

I'm feeling stuck. I currently have a basic fullCalendar setup for the User model in Rails. I want to add 2 buttons, allowing the User to separate the calendar into two views. One view would display only their own events, while the other would show al ...

eliminate the firebase firestore query using onSnapshot

Seeking assistance with the following code snippet: firebase.firestore() .collection("chatrooms") .doc(`${chatId}`) .collection(`${chatId}`) .orderBy("timestamp") .limit(50).onSnapshot((snapshot) => { //performing oper ...

Setting a dynamic default value for a Combobox using React Widgets

Currently delving into the world of javascript, I am working on creating a web client that showcases data from a database. Utilizing react.js and integrating react-widgets for some user-friendly widgets. One widget in particular, the combobox, pulls its da ...

What is the function of '@' symbol in coding?... obtain {ModuleName} from '@ModuleName'

What is the significance of the '@' symbol in imports? I've noticed that various modules like '@react-navigation', '@babel', and others use the '@' symbol. Does this symbol serve a specific purpose, or is it s ...

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]) ...

How can a div tag and its class be nested using CSS in Angular?

Can someone help me with nesting a div tag with the "error" class in CSS? <div [class]="{error: condition}">{{ message }}</div> I want to know how to have the .error selector inside the div selector in the CSS file. Note: The error ...

What is the best way to showcase an ajax response on an HTML webpage?

Apologies for the length of the code, but I'm looking to condense it while maintaining the same functionality. Is there an alternative approach or method that could achieve the same results? I receive data from PHP, which is then passed to JavaScript ...

Converting an array of objects into a dictionary using TypeScript

I'm attempting to convert an array of objects into a dictionary using TypeScript. Below is the code I have written: let data = [ {id: 1, country: 'Germany', population: 83623528}, {id: 2, country: 'Austria', population: 897555 ...

Display a loading bar or prevent any user interface actions until the server has finished generating the file

I am currently developing a force directed layout using d3.js on data retrieved from an MS SQL server database. I'm creating the json file with a python script and running it on a local server using python -m SimpleHTTPServer. My goal is to establish ...

The functionality of the TURF booleanwithin feature is malfunctioning and not producing the

Currently, I am working on validating whether a polygon is completely within another polygon. However, there are cases where more complex polygons should return false, but turf interprets them as valid. If you'd like to see the sandbox, click here: ...

What specific checks and alerts are triggered by React.StrictMode?

When utilizing React.StrictMode and React.Fragment, according to the React documentation: Both Fragment and StrictMode do not display any visible UI. Instead, they trigger additional checks and warnings for their child components. Question: What specif ...

Reorganizing divisions with Dojo

I came across a thread on StackOverflow that was similar to what I'm looking for. jQuery removing an element and renumbering remaining elements However, since we don't use jQuery but instead rely on Dojo, I'm unsure how to achieve the same ...

The modal form vanishes without any action when the form is clicked outside

Everything was working fine with the form submission until I turned it into a modal using Bootstrap. Now, when the form is rendered in the modal, users can tab and type without any issues. However, if they click on any element within the modal (including t ...

Maintaining the $index value across all pagination pages in AngularJS while matching it with the items in the data list

Is there a way to maintain the original $index numbers in my list data after pagination? For example, if data.length is 50 and they start from index 0, the first page contains 10 items ending at index 9. The next item on the second page should start at in ...

Launching the MEAN stack application into production

After completing a web app at an enterprise level, utilizing Vue for the front end, Node for the backend, and MongoDB as the database, we faced the challenge of hosting them separately during development. However, this setup may not be suitable for product ...