I have a service that wraps $http with my functions returning a deferred object.
My interface:
export interface MyServiceScope {
get: ng.IPromise<{}>;
}
My class:
export class MyService implements MyServiceScope {
static $inject = ['$http', '$log'];
constructor(private $http: ng.IHttpService,
private $log: ng.ILogService,
private $q: ng.IQService) {
this.$http = $http;
this.$log = $log;
this.$q = $q;
}
get(): ng.IPromise<{}> {
var self = this;
var deferred = this.$q.defer();
this.$http.get('http://localhost:8000/tags').then(
function(response) {
deferred.resolve(response.data);
},
function(errors) {
self.$log.debug(errors);
deferred.reject(errors.data);
}
);
return deferred.promise;
}
}
The compilation is failing with the following error:
myservice.ts(10,18): error TS2420: Class 'MyService' incorrectly implements interface 'MyServiceScope'.
Types of property 'get' are incompatible.
Type '() => IPromise<{}>' is not assignable to type 'IPromise<{}>'.
Property 'then' is missing in type '() => IPromise<{}>'.
For reference, here is the IPromise definition from DefinitelyTyped. The IQService.defer()
call returns an IDeferred
object, and then deferred.promise
returns IPromise object.
I'm not sure if I'm using the wrong definitions in my interface, or not returning the deferred object the same way. Any input would be greatly appreciated!
$q is integrated with the $rootScope. Scope Scope model observation mechanism in AngularJS, which means faster propagation of resolution or rejection into your models and avoiding unnecessary browser repaints, which would result in flickering UI. Q has many more features than $q, but that comes at a cost of bytes.
What Is Promise in Angular? Promises in Angular provide an easy way to execute asynchronous functions that use callbacks, while emitting and completing (resolving or rejecting) one value at a time. When using an Angular Promise, you are enabled to emit a single event from the API.
Promises in AngularJS are provided by the built-in $q service. They provide a way to execute asynchronous functions in series by registering them with a promise object. {info} Promises have made their way into native JavaScript as part of the ES6 specification.
$q is an angular defined service. It's the same as new Promise(). But $q takes things to the next level by enhancing additional feature that developers can use to perform complex tasks more simply. resolve(value) – resolves the derived promise with the value.
In your interface you defined a property get
and in the service implementation it's a function get()
. What you probably want is a function, so the interface should be:
export interface MyServiceScope {
get(): ng.IPromise<{}>;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With