Exploring the capabilities of Angular's ngResource library and how it

Currently, I am developing a Twitch app and instead of using $http, I opted for ngresource to explore new possibilities. However, I encountered an issue with the offline tab where the users are visible but their logo or username is not displayed. This happens because the stream promises return null for offline users, making it impossible to retrieve the logo/username. I am seeking help on how to filter my $scope.all array and group the offline users under the offline tab. Any assistance would be highly appreciated!

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'
          }
      }
    })
  };
})

Answer №1

The ng-click function in your Offline tab needs to be corrected. Replace the current code:

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

with this:

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

For more details, check out this link: http://codepen.io/anon/pen/KgLmjJ?editors=0001

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Foreign keys in a one-to-many relationship with Sequelize.js

I am in the process of developing a survey application using Node.js/Express and MySQL incorporating Sequelize.js ORM. However, I am encountering difficulties while establishing the relationship between the two models. My goal is to have the Questions&apo ...

How to completely disable a DIV using Javascript/JQuery

Displayed below is a DIV containing various controls: <div id="buttonrow" class="buttonrow"> <div class="Add" title="Add"> <div class="AddButton"> <input id="images" name="images" title="Add Photos" ...

Aligning a picture at the center of the screen with CSS - Various screen and image sizes

For my project, I need to design a web page with a single image perfectly centered both vertically and horizontally on the screen. Here are the specific requirements: The client's screen size is unknown (mobile) The image will be user-defined with u ...

ReactJS component experiencing issues with loading images

In my React project, there is a directory containing several images, and I am attempting to import them all into a carousel using Bootstrap. The current code looks like this: import Carousel from 'react-bootstrap/Carousel'; const slideImagesFold ...

Guide the user to a specific website and replicate the user's action of pressing the down arrow or clicking a button three consecutive times

Currently, I am facing an issue with a WordPress slider that lacks anchors for linking to specific sections. I am wondering if there is a way to direct a user to a URL and simulate the action of pressing the down arrow or clicking a button multiple times ...

Angular JS - Selecting Directives on the Fly

I'm currently developing an application where users can choose from various widgets using a graphical user interface (GUI). My plan is to integrate these widgets as angular directives. THE CONTROLLER $scope.widgets = ['one', 'two' ...

What is the best way to establish and maintain lasting connections with the Firebase database while utilizing the superagent

Currently, I am following the Firebase Functions documentation on enhancing Firebase database performance. I have provided the code snippet below for your reference. const request = require('superagent'); const functions = require('fireba ...

Tab knockout binding

I have a section in my HTML with 2 tabs. The default tab is working properly, but when I attempt to switch to the other tab, I encounter an error. Can anyone provide assistance in determining why this error occurs? Here is the HTML code: <ul class="na ...

Successful Ajax Form Submission but Fails to Receive Response

I am currently working on a feature where users can select a record from a menu to delete it from the database. Below this menu, there is a table displaying all records from the database. Even though the record gets deleted and reflects in the table upon m ...

Guide to invoking the NPM request multiple times within the mocha before hook

Can anyone advise on the correct way to call request multiple times (2 times) in mocha before hook? I am currently facing an issue where I get an error saying 'done() called too many times'. describe('...', function(){ before(functio ...

What is the best way to retrieve the updated value following a mutation in Vuex?

In my Vuex module, I have a simple setup for managing a global date object: import moment from 'moment'; const state = { date: moment() } // getters const getters = { date: state => state.date, daysInMonth: state => state.dat ...

Using DefaultSeo does not override NextSeo in every component

I am looking to dynamically change the Head tag using next-seo. While browser validation will show NEXTSeo for individual pages, Twitter, Firebase's card validation tool, and others will default to next-seo-config.js. Does anyone have a solution? S ...

Timing issues with setInterval and setTimeout are causing them to execute at the incorrect moments

I am struggling with changing the background image using setInterval and setTimeout every x seconds. The issue I am facing is that the timer is not working as intended, causing images to change instantly instead. let images = ['background1.jpg&apo ...

Iterate through the complex array of nested objects and modify the values according to specified conditions

I am currently iterating through an array of objects and then delving into a deeply nested array of objects to search for a specific ID. Once the ID is found, I need to update the status to a particular value and return the entire updated array. Issue: Th ...

ES6 syntax specification allows for the use of a fat arrow function for declaring React components

When learning React, I have noticed two different ways of declaring components. The first is using the classic fat arrow syntax with a return statement. const Component = () => { return ( <div>Hello</div> ) } Recently, I came ...

Is npm installation specifically for a node server?

I'm in the process of developing a React app with webpack and utilizing npm to install different front end packages such as tabs, D3, and more. As I plan for production, I'm wondering if I specifically need to run my server as a Node server given ...

Customize your webpage's style to reflect your unique identity with user

Is there a way to allow users to customize the style of a webpage? I know I need multiple CSS files, but how can I implement the code that enables this customization based on user preferences? ...

Retrieve the text content of the initial li element within each ul

I have numerous <ul> lists and I'm attempting to extract the text from the first li element of each list. The HTML markup is straightforward: <ul> <li>abc</li> <li>def</li> <li>ghi</li> </u ...

The grid images transition at set intervals using jQuery or another JavaScript framework

I am facing a challenge with developing an image grid that transitions some images at random intervals using either jQuery or another method in JavaScript. It's important to note that I don't want all the images to change simultaneously; each gro ...

What is the solution to fixing the JSON parsing error that says 'JSON.parse: bad control character in string literal'?

When sending data from NodeJS Backend to the client, I utilize the following code: res.end(filex.replace("<userdata>", JSON.stringify({name:user.name, uid:user._id, profile:user.profile}) )) //No errors occur here and the object is successfully stri ...