先に質問した、
AngularJSでのPromiseの返し方について(変数に繰り返し値を設定したい)
の続きです。
TypeError: Icecast.then is not a function
のエラーは出なくなったのですが、今度は別のところで問題が出ています。
実現したいことは上記の質問とほぼ同じで、AngularJS 1.6.4を使って、あるURLから返ってくるJSONの状態に応じた内容を随時ページに反映させたいと考えています。
MainController
の中の$interval
で繰り返しをさせたいのですが、コンソールには最初にIcecast was called.
と$http successful.
がそれぞれ1回だけしか表示されず、その後loop
の表示が繰り返されます。
Icecast
factoryの中身を繰り返し実行させて、ほぼ1秒ごとにURLにアクセスさせたいのですが、それが繰り返されていないようです。
どのようにしたらよいでしょうか。
よろしくお願いします。
コードは少し変えたので、改めて書きます。
index.html
lang
1<!doctype html> 2<html ng-app="app"> 3 <head> 4 <script src="bower_components/angular/angular.min.js"></script> 5 <script src="getmetadata.js"></script> 6 </head> 7 <body> 8 <section id="main" ng-controller="MainController"> 9 <div ng-bind="state"></div> 10 </section> 11 </body> 12</html>
getmetadata.js
lang
1angular 2 .module('app', []) 3 .controller('MainController', ['$scope', '$interval', 'Icecast', MainController]) 4 .factory('Icecast', ['$http', '$q', Icecast]); 5 6function MainController($scope, $interval, Icecast) { 7 $scope.state = 'offline'; 8 var t = $interval(function() { 9 Icecast.then(function(data) { 10 console.log('loop'); 11 if (data.icestats !== undefined && data.icestats.source !== undefined) { 12 if ($scope.state === 'offline') { 13 $scope.state = 'now live!'; 14 } 15 } else { 16 if ($scope.state === 'now live!') { 17 $scope.state = 'offline'; 18 } 19 } 20 }); 21 }, 1000); 22} 23 24function Icecast($http, $q) { 25 console.log('Icecast was called.'); 26 var d = $q.defer(); 27 28 return $http({ 29 method: 'GET', 30 url: 'http://live.oguradio.com:8000/status-json.xsl', 31 headers: { 32 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 33 'Origin': undefined 34 } 35 }) 36 .then(success, fail); 37 38 function success(response) { 39 console.log('$http successful.'); 40 d.resolve(response.data); 41 return d.promise; 42 } 43 44 function fail(response) { 45 console.log('$http failed.'); 46 d.resolve(response); 47 return d.promise; 48 } 49}
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/04/20 13:07
2017/04/20 13:11
2017/04/20 13:32
2017/04/20 13:44 編集
2017/04/20 13:49