Angular ngresource和不同的承诺

时间:2016-10-27 23:34:37

标签: javascript angularjs arrays angular-promise angularjs-ng-resource

我正在制作一个抽搐的应用程序。我知道可以用$ http轻松完成,但我决定尝试使用ngresource。我遇到的问题是离线标签。用户显示但不显示徽标或用户名。我知道这是因为流承诺为离线的用户返回null,因此我无法检索徽标/用户名。无论如何,我可以以某种方式过滤我的$ scope.all数组并将脱机用户置于脱机选项卡下?任何帮助将不胜感激!

http://codepen.io/labanch/pen/OXdKmK?editors=1011

  .controller('TwitchController', ['$scope','$q', 'TwitchAPIChannel', function($scope, $q, TwitchAPIChannel) {  

    var users = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];  
    //var offlineUsers = [];

    // Create promise for each channel/stream and store both in an empty object
    var channelPromises= users.reduce(function(map, user) {
        map[user] = TwitchAPIChannel.Channels.get({channel: user}).$promise;
        return map;
    }, Object.create(null));

    var streamPromises = users.reduce(function(map, user) {
        map[user] = TwitchAPIChannel.Streams.get({channel: user}).$promise;
        return map;
    }, Object.create(null));



    // Calling promises for each channel/stream
    $q.all(channelPromises).then(function(channels) {
        $scope.allUsers = [];
       //pushing all channels to the allUsers array
        angular.forEach(channels, function(channel) {   
          $scope.allUsers.push(channel);
        });
    });

    $q.all(streamPromises).then(function(streams) {
       $scope.onlineUsers = [];
       var offlineUsers = [];
       $scope.offlineUsers = [];
       angular.forEach(streams, function(stream) {
         if(stream.stream){
           $scope.onlineUsers.push(stream);
         } else {
           $scope.offlineUsers.push(stream);
         }
       });
    });

  //tabs
  this.tab = 1;
  this.setTab = function (tabId) {
      this.tab = tabId;
  };
  this.isSet = function (tabId) {
      return this.tab === tabId;
  };

  }])

 // Twitch API Factory using $resource
 .factory('TwitchAPIChannel', function TwitchAPIFactory($resource){
  return {
    Channels: $resource('https://api.twitch.tv/kraken/channels/:channel', {}, {
      get: {
          method: 'GET',
          headers: {
              Accept: 'application/vnd.twitchtv.v3+json',
              'Client-ID': 'haibznywychj91wl2j76x1v1mx1rgwf'
          }
      }
    }),
    Streams: $resource('https://api.twitch.tv/kraken/streams/:channel', {}, {
      get: {
          method: 'GET',
          headers: {
              Accept: 'application/vnd.twitchtv.v3+json',
              'Client-ID': 'haibznywychj91wl2j76x1v1mx1rgwf'
          }
      }
    })
  };
})

1 个答案:

答案 0 :(得分:1)

您的离线标签上的点击是错误的。改变它:

ng-click="tab = tab==2 ? a : 1"

到此:

ng-click="tab = tab==3 ? a : 3"

见这里:http://codepen.io/anon/pen/KgLmjJ?editors=0001