admin管理员组

文章数量:1289876

How to get json data from url and save them into the const variable in TypeScript?

const data = (get json from url);

Output:

data = [
                {
                    "name": "Peter",
                    "age": "20"
                },
                {
                    "name": "John",
                    "age": "25"
                }
            ];

How to get json data from url and save them into the const variable in TypeScript?

const data = (get json from url);

Output:

data = [
                {
                    "name": "Peter",
                    "age": "20"
                },
                {
                    "name": "John",
                    "age": "25"
                }
            ];
Share Improve this question edited Jun 1, 2018 at 11:47 Rav asked Jun 1, 2018 at 11:42 RavRav 331 gold badge1 silver badge6 bronze badges 5
  • 1 to my knowledge, a const variable cant be changed after it is initialised. you would need to use var – mast3rd3mon Commented Jun 1, 2018 at 11:47
  • The internal state of a const variable is still modifiable in TypeScript. typescriptlang/docs/handbook/variable-declarations.html – Rav Commented Jun 1, 2018 at 11:50
  • as quoted, const is an augmentation of let in that it prevents re-assignment to a variable – mast3rd3mon Commented Jun 1, 2018 at 11:51
  • 1 @mast3rd3mon const numLivesForCat = 9; const kitty = { name: "Aurora", numLives: numLivesForCat, } // Error kitty = { name: "Danielle", numLives: numLivesForCat }; // all "okay" kitty.name = "Rory"; kitty.name = "Kitty"; kitty.name = "Cat"; kitty.numLives--; – Rav Commented Jun 1, 2018 at 12:31
  • maybe so, but thats not what you are trying to do – mast3rd3mon Commented Jun 1, 2018 at 12:34
Add a ment  | 

1 Answer 1

Reset to default 9

You can use fetch API , here's the sample

I've use a dynamic variable , since constant cannot be re-assigned once the response is generated.

   let data  = ''

 fetch('https://jsonplaceholder.typicode./ments')
  .then(function(response) {
    return response.json();
  })
  .then(function(myJson) {

    data=myJson
 console.log(data)
  });
  
 

hope this helps you :)

本文标签: javascriptHow to get json data from url and save it to the const variable TypeScriptStack Overflow