user526206 user526206 - 4 months ago 18
AngularJS Question

How to use angularjs promise for some object

I am learning angularjs promise and want to implement in my code. I am trying to use a promise in a function which invoke before the object initialization. Here is a code

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


I want that when event occur for turnOffLocalAudio it will wait until $scope.currentCall initialize. One way to solve this by creating a timer task to check the $scope.currentCall object until it resolved. Is there any good way by using angularjs promise API?



update my question with promise implementation

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

Answer

What you want is some function that returns a promise. I just named it getCurrentCall.

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

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

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

Then you'd do this in your turnOffLocalRadio function:

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

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