Currently I’m working on Twitch json api project and have issue, I’m getting data from api with $.getJSON call and only after it should Angular start working and how is it possible?
var app = angular.module('MyApp', []);
// Twitch channel names
var channelNames = ["freecodecamp", "storbeck", "terakilobyte", "habathcx","RobotCaleb","thomasballinger","noobs2ninjas","beohoff"];
var channels = [];
// Get Channel Name
function getChannel(name) {
$.getJSON('https://api.twitch.tv/kraken/channels/'+ name, function(data) {
console.log(data.display_name);
channels.push({
name: data.display_name,
status: Boolean(data.status),
title: data.status || 'Channel is Offline'
});
});
}
channelNames.forEach(getChannel);
app.controller('viewController', function() {
this.channels = channels;
});
hi man , you need to work with $http and $q Promise
in your example the angular when run can not understand the what is the outside of his world
try that
var app = angular.module('MyApp',[]);
app.controller('viewController',[ '$http', function($http){
// array of Channels Name
var channelNames = [
"freecodecamp",
"storbeck",
"terakilobyte",
"habathcx",
"RobotCaleb",
"thomasballinger",
"noobs2ninjas",
"beohoff"
];
// Api Url
var apiUrl= 'https://api.twitch.tv/kraken/channels/';
// Channel Object
function Channel( name , status , title ){
this.name = name ? name : 'default Name' ;
this.status = Boolean(status) ;
this.title = status || 'Channel is Offline' ;
}
var self = this;
// channels array
self.channels = [];
// method to get details for given Channel name
self.getDetails = function(name , success , error ){
$http.get(apiUrl+ name ).then(success ,error );
};
// when request success
self.pushChannel = function(result){
var res = result.data;
self.channels.push(new Channel(res.display_name ,res.status , res.status ));
};
// when request have an error
self.handelError = function(error){
// hrere you can handel error
// mybe you can reload the channel again
}
// method to get all channels details
self.getChannelsDetails = function(){
for(var i =0;i< channelNames.length ; i++ ){
self.getDetails(channelNames[i],self.pushChannel, self.handelError);
}
};
// invoke method to get all channels datails
self.getChannelsDetails();
}]);