如何使用angularjs承诺某些对象

时间:2016-07-14 11:05:58

标签: angularjs angular-promise

我正在学习angularjs的承诺,并希望在我的代码中实现。我试图在对象初始化之前调用的函数中使用promise。这是一个代码

$scope.turnOffLocalAudio = function () {
    if ($scope.currentCall) {
        if ($scope.currentCall.chat) {
            $scope.currentCall.chat.offLocalAudio(false);
        }
    }
}

我希望当turnOffLocalAudio发生事件时,它会等到$ scope.currentCall初始化。解决此问题的一种方法是创建一个计时器任务来检查$ scope.currentCall对象,直到它解决。使用angularjs promise API有什么好办法吗?

使用承诺实施更新我的问题

 app.controller('videoChat', function ($rootScope, $scope,$q) {

var deferred = $q.defer();

     $scope.invite = function () {
    // some variable ...
    var chat = new Chat(function uiCallback(action, options) {

            // other methods ...
         if (action === "peer.call.localstream") {
            _displayMessage("Starting local stream");
            _findElement('#myVideo').prop('src', URL.createObjectURL(options.payload));
            _findElement('#myVideo').css('display', 'inline');
            deferred.resolve();
        }

    });
    $scope.currentCall = {
        roomId: roomId,
        chat: chat,
        opponentId: String($scope.currentPatientId),
    };
    chat.connectSocket(remoteSocket, peerURL, id, roomId);
};

    $scope.changeLocalVideoStream = function () {
    var promise = deferred.promise;
    promise.then(function (result) {
        if ($scope.currentCall) {
            if ($scope.currentCall.chat) {
                    $scope.currentCall.chat.toggleLocalWebCam($scope.showLocalVideo);
            }
        }
    }, function (reason) {
        $log.error("unable to turn off local camera");
    });
}

1 个答案:

答案 0 :(得分:0)

你想要的是一些返回承诺的函数。我把它命名为getCurrentCall。

function getCurrentCall() {
  var deferred = $q.defer();

  if (!$scope.currentCall) {
    $scope.currentCall = 'foo';
  }

  deferred.resolve();
  return deferred.promise;
}

然后你在turnOffLocalRadio函数中执行此操作:

$scope.turnOffLocalAudio = function() {
  getCurrentCall().then(function() {

    if ($scope.currentCall.chat) {
      $scope.currentCall.chat.offLocalAudio(false);
    }
  }, function() {
    // unable to get CurrentCall
  });
};