对象为$ http params

时间:2015-06-17 13:02:02

标签: javascript angularjs

我想使用angulars $http服务向API发出GET请求,并将对象作为url参数,但它并没有按预期工作。

预期结果:

http://something.com/test?page=20&filter=hello

有效结果(从应用程序复制):

api/cameras?query=%7B%22filterByFields%22:%7B%7D,%22page%22:0,%22pageSize%22:20%7D

转换为:

{"filterByFields":{},"page":0,"pageSize":20}

根据params用法的角度文件:

  

将使用paramSerializer序列化并附加为GET参数的字符串或对象的映射。

cameraApiService

public getCameras(query) {
        var deferred = this._q.defer();
        this._http.get(this._baseUrl, {
            params: {
                query: query
            }
        })
        .success((result, status, headers) => 
                deferred.resolve({
                    items:      result.items,
                    page:       result.page,
                    pageSize:   result.pageSize,
                    totalCount: result.total
                })
            )
        .error((msg, code) => {
            deferred.reject(msg);
            console.error(code, msg);
        });
        return deferred.promise;
    }

cameraListController

public loadData() {
        this.loaded     = false;
        this.items      = [];

        var options = {
            filter:         this.filter,
            filterByFields: this.filterByFields,
            orderBy:        this.orderBy,
            page:           this.page,
            pageSize:       this.pageSize
        };

        this._cameraApi.getCameras(options)
            .then(result => {
                this.items          = result.items;
                this.totalCount     = result.totalCount;
                this.pageSize       = result.pageSize;
                this.page           = result.page;
                this.loaded         = true;
            }, error => {
                this._toaster.pop({ type: "error", body: "Unknown error occured: " + error });
                this.loaded  = true;
            });
    }

2 个答案:

答案 0 :(得分:1)

你犯了一个错误

而不是

this._http.get(this._baseUrl, {
   params: {
     query: query
   }
})

直接将您的查询对象传递给这样的参数

this._http.get(this._baseUrl, {
    params: query
})
通常它应该有用。

答案 1 :(得分:0)

我认为" params"应该是JSON.stringify

var query= JSON.stringify({
    params: {
        page:     page,
        filter:   filterField, 
    }
});

然后:

$http({
  method:'GET',
  url:baseuri + "test",
  query
});