【问题标题】:How to get json data from url and save it to the const variable [TypeScript]如何从 url 获取 json 数据并将其保存到 const 变量 [TypeScript]
【发布时间】:2018-11-11 13:13:04
【问题描述】:

如何从url获取json数据,并保存到TypeScript的const变量中?

const data = (get json from url);

输出:

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

【问题讨论】:

  • 据我所知,const 变量在初始化后无法更改。你需要使用var
  • const 变量的内部状态在 TypeScript 中仍然可以修改。 typescriptlang.org/docs/handbook/variable-declarations.html
  • 如引用,const is an augmentation of let in that it prevents re-assignment to a variable
  • @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--;
  • 也许是这样,但这不是你想要做的

标签: javascript json typescript ecmascript-6


【解决方案1】:

您可以使用 fetch API ,这是示例

我使用了动态变量,因为一旦生成响应,就无法重新分配常量。

   let data  = ''

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

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

希望这对你有帮助:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-19
    相关资源
    最近更新 更多