Waiting for the response from $http in Angular2

In almost all REST requests, I require the user's ID to be included.

After logging in a user, I store the token in local storage and pass the ID to user.service.ts (using the function setUserId(userId);). However, when authenticating a user using only the token (e.g., if the user is already logged in but the page is refreshed), I attempt to retrieve the user's ID from the User object obtained through a REST request using the token.

This section of my code appears as follows:

getUser() {
    var authToken = localStorage.getItem('authorization')

    if(!this.userPromise){
      let headers = new Headers();
      headers.append('Content-type', 'application/json');
      headers.append('Authorization', authToken);

      this.userPromise = this.http.get(
        'http://localhost:8080/api/user',
        { headers }
      ).toPromise()
        .then((res) => res.json());
    }

    return this.userPromise;
  };




getUserId(){
    var $self = this;

    if($self.userId){
      return $self.userId;
    } else {
      $self.getUser().then(function(result){
        $self.setUserId(result.id);
        console.log(result.id);
        return result.id;
      });
    }
  }

Whenever a request requires the user ID, I utilize the getUserId() method and check whether the user ID is defined. If it is defined, I respond with that data; otherwise, I aim to retrieve the data from the getUser() function.

I am facing a problem where this request is asynchronous, causing the "task" service, for example, to receive the userId value as undefined before waiting for the updated value.

How can I address this issue?

---EDIT

Here is a sample request that does not wait for a response;

 getUserTasks() {
    // return this.userService.getUserId();
    var userId = this.userService.getUserId();

    return this.http.get(
      'http://localhost:8080/api/private/'+userId+'/tasks'
      // 'http://localhost:8080/api/private/1/tasks'
    )
    .toPromise()
      .then((res) => res.json());
  }

Answer №1

After much exploration, I have discovered a solution - the key lies in utilizing async/await functions properly within the getUserTasks() method:

 async getUserTasks() {
    let userId = await this.userService.getUserId();

    return this.http.get(
      'http://localhost:8080/api/private/'+userId+'/tasks'
    )
    .toPromise()
    .then((res) => res.json());
  }

--- UPDATE ---

Ultimately, if someone encounters the same issue, moving the changes up to the authentication process proved to be effective. This approach allows access to the userId from any part of the application through the UserService.getUserId() service.

During user login, all data can be stored in a variable. When only authentication is performed, the isLoggedIn() function can be modified to utilize async/await. If a ticket exists, an authentication request is sent to retrieve the User object.

If the User object is successfully obtained, true is returned and the userId is set in the userId service. In case of an error (no credentials), the log-out action is triggered in the getUser() function.

This solution not only provides essential data but also enhances the verification process in the guard feature of the application.

async isLoggedIn() {
    var $self = this;

    if(localStorage.getItem("authorization")){
      var user = await $self.getUser();
      this.setUserId(user.id);

      return true;
    } else {
      return false;
    }
  }

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

Unable to access the "target" property while transferring a value from child to parent component

Within my project, the student component is considered a child component of the main app component. Inside the template of the student component, there is an input element defined like so: <input type='text' #inputbox (keyup)='onkeyUp(i ...

My customized mat-error seems to be malfunctioning. Does anyone have any insight as to why?

Encountering an issue where the mat-error is not functioning as intended. A custom component was created to manage errors, but it is not behaving correctly upon rendering. Here is the relevant page code: <mat-form-field appearance="outline"> < ...

The ChartistJs is unable to find the property '_index' of an undefined value, either being 0 or null

I recently incorporated chartistJS to display charts on my website. I have successfully implemented the 'onClick' function provided by chartist. Here is a snippet of the code I used: public horizontalBarchartoptions = { 'onClick&apo ...

Fixing errors with observables in an Angular 2 project using Rx

var foo = Observable.create(function(observer){ try{ console.log('hey there'); observer.next(22); throw new Error('not good at all'); setTimeout(function(){ observe ...

AmCharts issue in NextJS - Unusual SyntaxError: Unexpected token 'export' detected

Encountered an error while trying to utilize the '@amcharts/amcharts4/core' package and other amchart modules in a NextJS project: SyntaxError: Unexpected token 'export' After searching through various resources, I came across a helpf ...

"Receiving an error message stating 'Was expecting 1 parameter, received 2' while trying to pass a useState function in TypeScript

I am encountering an issue with a component where I pass a useState setter to a utility function: export interface IData { editable: string[]; favourited: string[]; } const [data, setData] = useState<IData | undefined>(undefined) useEffect(() = ...

React Testing Library - Screen debug feature yields results that may vary from what is displayed in the

Greetings to all who come across this message. I have developed a tic-tac-toe game in typescript & redux with a 3x3 grid, and now I am facing some challenges while trying to write unit tests for it. Consider the following game board layout where X represen ...

Troubles with implementing child routes in Angular 6

I'm having trouble getting the routing and child routing to work in my simple navigation for an angular 6 app. I've configured everything correctly, but it just doesn't seem to be working. Here is the structure of my app: └───src ...

What is the reason for instances being compatible even if their class constructors do not match?

Why are the constructors in the example below not compatible, but their instances are? class Individual { name: string; age: number; constructor(name: string, age: number) { this.name = name; this.age = age; } } class Worker { name: st ...

The Material UI button shifts to a different row

I need help adjusting the spacing between text and a button on my webpage. Currently, they are too close to each other with no space in between. How can I add some space without causing the button to move to the next line? const useStyles = makeStyles((the ...

"Ensure that a directive is universally accessible throughout an angular2 final project by registering it

I have created a custom directive that I want to use throughout my application. How can I register my directives so they are accessible in the entire application? I have found outdated solutions for this issue and need a solution specific to Angular 2 fina ...

What is the best way to attach events to buttons using typescript?

Where should I attach events to buttons, input fields, etc.? I want to keep as much JS/jQuery separate from my view as possible. Currently, this is how I approach it: In my view: @Scripts.Render("~/Scripts/Application/Currency/CurrencyExchangeRateCreate ...

Google's reCAPTCHA issue: systemjs not found

Currently, I am attempting to integrate Google's reCAPTCHA into an Angular application by following a helpful tutorial found here. However, I have encountered a problem as the systemjs.config.js file seems to be missing from my Angular CLI project. An ...

Inject parameter into MdDialog in Angular Material 2

I am currently utilizing Angular Material 2 and I have a requirement to display a dialog window using MdDialog that contains information about a user stored in Firebase. @Injectable() export class TweetService { dialogRef: MdDialogRef<TweetDialogCom ...

Typescript Tooltip for eCharts

I'm working on customizing the tooltip in eChart v5.0.2 using Typescript, but I'm encountering an error related to the formatter that I can't seem to resolve. The error message regarding the function keyword is as follows: Type '(param ...

Invoke cloud functions independently of waiting for a response

Attempting a clever workaround with cloud functions, but struggling to pinpoint the problem. Currently utilizing now.sh for hosting serverless functions and aiming to invoke one function from another. Let's assume there are two functions defined, fet ...

Manipulate values within an array when a checkbox is selected or deselected

I am developing an Angular application where I have created a checkbox that captures the change event and adds the checked value to an array. The issue I am facing is that even if the checkbox is unchecked, the object is still being added to the array. D ...

Angular 11 is indicating that the type 'File | null' cannot be assigned to the type 'File'

Hey there, I'm currently diving into Angular and I'm working on an Angular 11 project. My task involves uploading a CSV file, extracting the records on the client side, and saving them in a database through ASP.NET Web API. I followed a tutorial ...

A comprehensive guide on using HttpClient in Angular

After following the tutorial on the angular site (https://angular.io/guide/http), I'm facing difficulties in achieving my desired outcome due to an error that seems unclear to me. I've stored my text file in the assets folder and created a config ...

Attempting to transpile JavaScript or TypeScript files for compatibility within a Node environment

Our node environment requires that our JavaScript files undergo Babel processing. Figuring out how to handle this has been manageable. The challenge lies in the fact that we have a mix of file types including .js, .jsx, .ts, and .tsx, which is not subject ...