【问题标题】:How to pass JSON array to a function in angularjs?如何将JSON数组传递给angularjs中的函数?
【发布时间】:2020-03-14 14:25:28
【问题描述】:

我是 angularjs 的新手。所以如果这个问题在你看来很愚蠢,请不要生气。

这是我的代码。

var songdata = [];
$scope.getData = function(){

    $http({
        url: 'getsongdata',
        method: 'GET',

      }).then(function(resp){
         songdata = resp.data;
         console.log(songdata);
      }, function(resp){
        alert("Error Occoured.");
        console.log(resp);
      });
    };

现在我想将此歌曲数据传递给 as。

var player = new Player(songdata);

但它给了我这个错误:

TypeError:无法读取未定义的属性“标题” 在新玩家 (player.js:24)

我可以在控制台上打印数据。但我无法将其作为参数传递。

更多代码:

var Player = function (playlist) {
    //console.log(playlist);
    this.playlist = playlist;
    this.index = 0;

    // Display the title of the first track.
    track.innerHTML = playlist[0].title;

    // Setup the playlist display.
    playlist.forEach(function (song) {
      var div = document.createElement('div');
      div.className = 'list-song';
      div.innerHTML = song.title;
      div.onclick = function () {
        player.skipTo(playlist.indexOf(song));
      };
      list.appendChild(div);
    });
  };

请帮我解决这个问题。

【问题讨论】:

  • 什么是console.log(playlist);?你也可以发一下吗?
  • 是的。是这样的: (2) [{…}, {…}] 0: 文件: "F:/Music/yellow" 嚎叫: "null" title: "yellow" proto: 对象 1:文件:“F:/Music/numb” 嚎叫:“null” 标题:“numb” proto:对象长度:2 proto:Array(0)
  • 你能不能在这行前面加上console.log(playlist);var player = new Player(songdata);来检查它是否是undefined
  • 它正在打印一些奇怪的 HTML 代码

标签: javascript json angularjs


【解决方案1】:

似乎您的 http 请求返回数据正常,但在您尝试初始化时存在调用顺序问题 - var player = new Player(songdata)。可以这样初始化试一下吗

.then(function(resp){
     songdata = resp.data;
     console.log(songdata);
     var player = new Player(songdata);
     //console.log(player);

最好将服务调用保存在服务文件中。

【讨论】:

  • 好吧,我已经尝试过了,但它在播放器与外部关联时出错。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-09
  • 1970-01-01
相关资源
最近更新 更多