AngularJS JSONP没有更新对象的键值

时间:2017-05-18 02:13:20

标签: javascript angularjs jsonp

我尝试使用channel.status回调函数更新//Second JSONP对象。

angular.element(document).ready(function() {
    channels = [];
    channel = {};

    followersAPI = followersAPI.replace(/theUser/, user);
    followersAPI = $sce.trustAsResourceUrl(followersAPI);

    // First JSONP
    $http.jsonp(followersAPI).then(function (response) {
        var follows = response.data.follows;

        for (var i = 0; i < follows.length; i ++) {
            var currentChannel = follows[i].channel;

            if (currentChannel.status == null) {
                currentChannel.status = "offline";
            }

            channel = {
                name: currentChannel.name,
                display_name: currentChannel.display_name,
                logo: currentChannel.logo,
                url: currentChannel.url,
                status: "loading"
            };

            streamAPI = "https://wind-bow.glitch.me/twitch-api/streams/";
            streamAPI += channel.name;
            streamAPI = $sce.trustAsResourceUrl(streamAPI);

            // Second JSONP
            $http.jsonp(streamAPI).then(function (response) {
                data = response.data;
                if (data.stream == null) {
                    channel["status"] = "offline";
                } else {
                    channel["status"] = data.stream.channel.status;
                }
            });
            channels.push(channel);
        }
    });
    $scope.channels = channels;
    console.log($scope.channels);
});

没有错误消息,但只更新了channel{}数组中的最后一个channels[]对象。

jsonp output

这是channel.status的HTML部分:

 <div id="channel-status" class="col-md-6">
        <a
        class="btn"
        href="{{channel.url}}"
        target="_blank">
            {{channel.status}}
        </a>
</div>

1 个答案:

答案 0 :(得分:0)

对于$http.jsonp中的异步调用for-loop,在其回调中,您只会获得最后定义的channel的实例。作为解决方案,您应该移动channel的所有内容进入Second JSONP

var currentChannel = follows[i].channel;

streamAPI = "https://wind-bow.glitch.me/twitch-api/streams/";
streamAPI += channel.name;
streamAPI = $sce.trustAsResourceUrl(streamAPI);

// Second JSONP
$http.jsonp(streamAPI).then(function (response) {
    data = response.data;
    if (currentChannel.status == null) {
        currentChannel.status = "offline";
    }

    channel = {
        name: currentChannel.name,
        display_name: currentChannel.display_name,
        logo: currentChannel.logo,
        url: currentChannel.url,
        status: "loading"
    };

    if (data.stream == null) {
        channel["status"] = "offline";
    } else {
        channel["status"] = data.stream.channel.status;
    }
    channels.push(channel);
});