James LeBorn
James LeBorn

Reputation: 221

How to assign JSON api received data to a variable in typescript?

My title say it all, I invoke an API which in return sends the data in JSON format, which I want to assign to a variable. here is my ajax code. Remember: I'm using it in an Angular application

I've tried to assign it to a variable, but it didn't worked.

$.ajax({
  url: 'https://randomuser.me/api/',
  dataType: 'json',
  success: function(data) {
    console.log(data);
  }
});

Upvotes: 0

Views: 146

Answers (1)

Anshuman Jaiswal
Anshuman Jaiswal

Reputation: 5462

You will have to use arrow function in order to get correct context as:

$.ajax({
  url: 'https://randomuser.me/api/',
  dataType: 'json',
  success: (data) => {
    console.log(data);
    this.abcVariable = data; //<====== Here

  }
});

Note: It's not good practice to use jQuery in Angular application, Angular provides http module for network things.

Upvotes: 1

Related Questions