如何在get方法angular2中传递多个prams

时间:2017-02-08 07:25:57

标签: angular http typescript

我使用以下代码获取get方法

this.required = {id:this.CategoriesId,fields:"courses.fields(largeIcon,instructor)",                  includes:"courses"};

        this.courseraService.getEachCategory ("categories", this.required)
                 .subscribe (
                      response => this.Courses = response,
                      error =>  this.errorMessage = <any>error,
                      () => console.log(this.Courses)

              );


      getEachCategory(model,data){

            this.url = this.heroesUrl + model;
            console.log(this.url);
                 console.log(data);
            var params = data;

            return this.http.get(this.url + params)
                  .map ( response => response.json())
                  .do( data => console.log ('All categories: ' + JSON.stringify(data) ) )
                  .catch(this.handleError);
      }

我试图将参数作为对象传递但在网址中出现以下错误

GET https://api.coursera.org/api/catalog.v1/categories[object%20Object]

2 个答案:

答案 0 :(得分:1)

您需要像这样创建服务网址:

let params: URLSearchParams = new URLSearchParams();
for (let key in data) {
  params.set(key, data[key]);
}

let options = new RequestOptions({search: params});

return this.http.get(this.url, options)...

此处记录:https://angular.io/docs/ts/latest/api/http/index/RequestOptions-class.html

https://angular.io/docs/ts/latest/api/http/index/URLSearchParams-class.html

答案 1 :(得分:0)

import {Http, Response, RequestOptions, URLSearchParams} from "@angular/http";

getEachCategory(model,data){
    this.url = this.heroesUrl + model;

    var args = new RequestOptions();
    args.search = new URLSearchParams();

    // you can also repeate for loop for data array
    args.search.append('key1', data[0].toString());
    args.search.append('key2', data[1].toString());
    args.search.append('key3', data[2].toString());
    return this._http.get(this.url, args)
    .map((res:Response) => res.json()).toPromise();
}