Thomas Zoé Thomas Zoé - 21 days ago 6
TypeScript Question

AngularJS how to use $q in Typescript

I am new at AngularJs and very new at Typescript.
I included Typescript in my AngularJs project but couldn't handle a service where i return a $q(function(){...})

my code looks like:

function foo(request, monitor, currentMonitorPropertys) {
var currentChart;
return $q(function (resolve) {
$http(request).success(function (chartResponse) {
...
resolve(monitor);
}).error(function(response){
...
});
});


I work with VS2013(TypeScript), if i implement this method like above, there comes an compilererror: Value of type 'IQService' is not callable. Did you mean to include 'new'?

So how could I implement the function with Typescript.
Thank you for your answer.

Answer

There are several ways to return a promise... $http returns a promise with each of its ajax calls, $timeout also returns a promise.

That being said you want to return a promise based upon something other than a scheduled event ($timeout, $interval) via $q you can do this...

// assume $q is injected into your service/controller/factory
// create a defer object
var defer = $q.defer();
// do something...
if (doSomething()){
  defer.resolve(); //something went right
else {
  defer.reject(); //something went wrong
}
//make sure you return out the promise, so the consumer can act upon it.
return defer.promise;

Also, $q has some nice helper methods to return a promise that you can use when you stub out some logic;

// this will a promise that will resolve with the value provided
return $q.when({some: 'result'});

// this will return a promise that will reject with the error specified
return $q.reject('some error message');