角服务承诺服务承诺

由网友(此年定人生)分享简介:所以,我有一个角度的应用程序,向服务器宁静的电话。有一个封装到服务器的调用的服务。我现在有上简单地返回从$ http服务承诺服务的方法。我想加到这个方法调用一些额外的处理,但我不知道该怎么做,因为承诺的异步特性。So, I've got an Angular app that makes restful calls...

所以,我有一个角度的应用程序,向服务器宁静的电话。有一个封装到服务器的调用的服务。我现在有上简单地返回从$ http服务承诺服务的方法。我想加到这个方法调用一些额外的处理,但我不知道该怎么做,因为承诺的异步特性。

So, I've got an Angular app that makes restful calls to the server. There is a service that wraps up the calls to the server. I currently have a method on the service that simply returns the promise from the $http service. I'd like to add some additional processing on that method call, but I'm not sure how to do it because of the asynchronous nature of the promise.

目前在打字稿:

class BoardService {
    private $http;

    constructor($rootScope: IRootScope, $http: ng.IHttpService) {
          this.$http = $http;
    }

    fetchBoard(id: number) {
        return this.$http.get("/api/board/" + id);
    }
}

我希望得到它是这样的:

I'd like to get it to something like this:

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

    });

    // return manipulated data; 
}

你会怎么做呢?

推荐答案

整蛊一句警告!由于承诺是异步的,任何基于从承诺本身必须返回一个承诺数据返回的数据。你想 fetchBoard2 来返回被曾经的 $ HTTP 承诺解决的承诺已经回来了,你已经操纵数据。为此,您可以角的 $ Q 服务。

Tricky sentence warning! Because promises are asynchronous, anything returning data based on data from a promise must itself return a promise. You want fetchBoard2 to return a promise that gets resolved once the $http promise has come back and you've manipulated the data. You do this with Angular's $q service.

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 extra deferred objects gets quickly fiddly, so you can use then to insert your own manipulation into the pipeline.

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

有关更多详细信息,这里的a好文章。

For more detail, here's a good article.

阅读全文

相关推荐

最新文章