Angular Service Promises

So, I have an Angular application that makes quiet calls to the server. There is a service that terminates calls to the server. I currently have a service method that simply returns a promise from the $ http service. I would like to add additional processing to this method call, but I'm not sure how to do this due to the asynchronous nature of the promise.

Currently in typescript:

class BoardService { private $http; constructor($rootScope: IRootScope, $http: ng.IHttpService) { this.$http = $http; } fetchBoard(id: number) { return this.$http.get("/api/board/" + id); } } 

I would like to do it something like this:

 fetchBoard2(id: number) { this.$http.get("/api/board/" + id).success(function(data) { // Manipulate the data }); // return manipulated data; } 

How do you do this?

+5
source share
2 answers

Compound Offer Warning! Because promises are asynchronous, everything that returns data based on data from a promise should be the promise itself. You want fetchBoard2 to return a promise that will be resolved after the $http promise returns and you process the data. You do this using the Angular $q .

 fetchBoard2(id: number) { var deferred = $q.defer(); $http.get("/api/board/" + id).success(function(data) { var newData = doSomething(data); deferred.resolve(newData); }); return deferred.promise; } 

Managing additional pending objects is quick, so you can use then to insert your own manipulations into the pipeline.

 fetchBoard3(id: number) { return $http.get(...).then(function(data) { return doSomething(data); }); } 

In more detail here is a good article .

+10
source

The $http module provides only the asynchronous version of XMLHttpRequest , so the signature you are looking for is not possible. If you do not want to fall back to another structure (for example, jQuery), you will have to use the returned Promise object.

Think of it as a factory object with which you register handlers that will be called when data returns. They can be chained, so if you want to process the data before passing it downstream, you can just do it in the handler that you register using the then method . Any result that you return in the handler will become data for the next then handler.

(Note that unlike success() , the argument to your handler is the type IHttpPromiseCallbackArg , not the data itself.)

0
source

All Articles