Angular-可以获取$ http参数吗? [英] Angular - Is possible to get the $http parameters?

查看:51
本文介绍了Angular-可以获取$ http参数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简短问题

我有这个:

let promise = $http.get('/api/users');

我可以得到诺言的参数吗?像这样:

Can I get the promise's parameters? Something like this:

let promise = $http.get('/api/users');

let parameters = promise.getParameters();

/*

parameters = {
   method: 'GET',
   url: 'api/users',
   // etc.
}

*/

我想在分页服务中传递诺言,然后可以更改url传递参数(上一页/下一页等)

I would like to make a Pagination service where I pass a promise and then I could change the url passing parameters (previous/next page etc.)

谢谢.

我需要更好地解释:

我想将主要"承诺传递给PaginationService.

I'd like to pass the "main" promise to a PaginationService.

this.paginator = {};

Paginator.make(this.paginator, function (page) {
   // this will be the "main" promise
   // page = 1
   return $http.get('/api/users', {
      params: {
         page: 1
      }
   });
});

// PaginatorService
this.make = function (scopePaginator, callback) {
   scopePaginator.next = function () {
      return callback(scopePaginator.current_page);
   };

   return callback().then(function (response) {
       // the response.meta contains all the data (current_page, etc.);

       angular.extend(scopePaginator, response.data);

       return scopePaginator;
   });

}

这就是我正在做的事情...

Something like this is what I'm doing...

推荐答案

生成请求的配置对象是响应对象的一部分.

The configuration object that generated the request is part of the response object.

var promise = $http.get('/api/users');

promise.then(function onSuccess(response) {
    var config = response.config;
    console.log(config.method);
    console.log(config.url);
    console.log(config.params);
});

因此,可以将来自$ promise的连续$ http调用链接起来.

Thus successive $http calls can be chained from the promise.

promiseNext = promise.then(function onSuccess(response) {
    var config = response.config;
    vm.data[config.params.page] = response.data;
    config.params.page++;
    //return promise for chaining
    return $http(config);
};


更新

一个返回页面直到页面编号 n 的函数:

var promiseUntilN = function(promise, n) {
    p = promise
        .then( function onSuccess(response) {
            var config = response.config;
            var page = config.params.page;
            vm.dataArray[page] = response.data;
            if ( page >= n ) {
                return vm.dataArray;
            } else {
                config.params.page++;
                return promiseUntilN($http(config), n);
            };
    return p;
};

用法:

vm.dataArray = [];
var n = 10;
var promise1toN = promiseUntilN($http.get('/api/users',{page: 1}), n);

promise1toN.then( function onSuccess( dataArray ) {
    console.log(dataArray);
}).catch( function onReject(response) {
    var page = response.config.param.page;
    console.log("Error on fetch of page ", page);
});

这篇关于Angular-可以获取$ http参数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆