$interval不能用于回调函数,angular js

$interval not working for callback function, angular js

本文关键字:angular js 函数 回调 interval 不能 用于      更新时间:2023-09-26

我是angularjs的初学者,如果我问了愚蠢的问题,请原谅。

function getCams(callback){
  var media_list = [];
  MediaStreamTrack.getSources(function(sourceInfos){
    var i=0;
    while(i!=sourceInfos.length){
      if (sourceInfos[i].kind == 'video'){
        var temp = [];
        temp.push(sourceInfos[i].id);
        temp.push(sourceInfos[i].label);
        media_list.push(temp);
      }
      i++;
    }
    callback(media_list);
  });
}
var app = angular.module('myApp', []).config(function($interpolateProvider){
    $interpolateProvider.startSymbol('{[{').endSymbol('}]}');
});
app.controller('myCtrl', function($scope, $interval) {
  $scope.cams = [];
  var checkcams = getCams(function(media_list){
    $scope.cams=media_list;
    $scope.$apply();
    console.log("test");
  });
  $interval(checkcams, 10000);
});

以上是我试图获得连接到系统的摄像机数量的代码,并试图在angular js中使用回调函数更新相同的代码,在这一行

$interval(checkcams, 10000);

我试图在每10秒后调用该函数,但此函数在页面加载后只运行一次,而不是每10秒后运行一次。

这个问题我已经看过了,它帮不了我。$interval未运行,angularjs

getCams不返回任何内容,因此$interval不工作。这是预期的行为。

您可以将代码重写为

//Wrap getCams call in a function
var checkcams = function(){
    getCams(function(media_list){
        $scope.cams=media_list;
        $scope.$apply();
        console.log("test");
    });
}
//Call it when view is launched
checkcams();
//set Interval
$interval(checkcams, 10000);

通过这样做

var checkcams = getCams(function(media_list){
$scope.cams=media_list;
$scope.$apply();
console.log("test");

});

你已经将checkcams设置为getCams返回的变量,而不是函数。

试试这个

function checkcams () {
    getCams(function(media_list){
        $scope.cams=media_list;
        $scope.$apply();
        console.log("test");
    });
}
$interval(checkcams, 10000);