动态URL参数基于数组Angular 2中的id数

时间:2017-07-24 20:58:35

标签: angular http typescript

我有一个名为selectedItems的数组,它是从多选下拉按钮填充的。如果选择了所有选项,SelectedItems可能如下所示:

this.selectedItems: SearchItem[]= [
  {"id":"abee232","itemName":"Attractions"},
  {"id":"b6b1a23","itemName":"Artists"},
  {"id":"08a58c8","itemName":"Performing Arts"},
  {"id":"444d047","itemName":"Sports"}
];

我需要添加id值,但是已经选择了很多,作为http GET请求中的参数。现在我的逻辑看起来像这样。

  private addRequestOptions(params: SearchItem[]): RequestOptions {
    let options: RequestOptions = new RequestOptions();
      options.params = new URLSearchParams();
    if (params != null) params.forEach((p: SearchItem) => {
      options.params.append("&collectionId", p.id);
    })
    console.log(options)
    return options;
  }

  sortResults(){
        let options: RequestOptions = this.addRequestOptions(this.selectedItems);
        this.pendingCardsService.collectionUuidUrl = 'http://address/cards/topbrands?perPage=25', options;
        this.pendingCardsBrandCollection();
  }

我的SearchItem界面如下所示:

export interface SearchItem {
  id?: string;
  itemName?: string;
}

现在,这会创建一个requestOptions对象,该对象的值为数组,但我的http请求不会在网络选项卡的查询字符串参数字段中显示此对象。似乎addRequestOptions()工作正常但未正确应用于get请求。目标是最终得到这样的URL:

'http://address/cards/topbrand?perpage=25&collectionId=idValue&collectionId=idValue&collectionId=idValue'

我被困在如何做到这一点。任何帮助/提示/建议将不胜感激。

更新/最终代码 我的问题是我在'http://address/cards/topbrands?perPage=25'中进行了硬编码?perPage = 25被读作params(理所当然),因此没有附加id,因为params已经存在。我的最终代码最终看起来像这样才能使它正常工作:

  fetchPendingCardsBrandCollection(ids: SearchItem[], pageSize = '25'):Observable<Card[]> {
    const params = new URLSearchParams();
    params.set('perPage', pageSize);
    ids.forEach(id => params.append('collectionId', id.id));
    return this.http.get(this.collectionUuidUrl, {params: params})
      .map(this.extractData)
  }

我的函数调用此http请求函数将SearchItems作为参数传递。非常感谢@Praveen M的帮助和@ Jota.Toledo的解决方案!

2 个答案:

答案 0 :(得分:1)

import { Observable } from 'rxjs/Observable';
import { Injectable } from '@angular/core';
import { Http, URLSearchParams } from '@angular/http';

export interface SomeInterface {
   // Define the properties of the JSON object sent as response from the backend
}

@Injectable()
export class SomeService {
   constructor(private _http: Http){}

   queryElements(ids: string[] = [], pageSize = 25): Observable<SomeInterface>{
      const params = new URLSearchParams();
      params.set('perPage', pageSize); // using set: replace the existing value of the query parameter "perPage" if exist.
      ids.forEach(id => params.append('collectionId', id)); // using append: allows multiple values for the query parameter "collectionId" 
      return 
       this._http.get("http://address/cards/topbrand",{params: params})
         .map(r => r.json())
         .catch(//handle error);
   }
}

答案 1 :(得分:-1)

通过为数据提供一个类型来更新现有的数据数组,以便在处理数组时有更少的错误空间。

&#13;
&#13;
// Add the class to a ts file
export class Args {
 id: string;
 itemName: strngs;
}

dropdownList: Args[] = [];

// Declare the selectedItems is a type of Args class
selectedItems: Args[] = [];


this.dropdownList = [
  {id:"abee232b6f3b06c3da1955fb270ced28", itemName:"Attractions"},
  {id:"b6b1a23b6a0ad3ab467284ca92bc7d59", itemName:"Artists"},
  {id:"08a58c804fa4eb462ad4e690a51864f6", itemName:"Performing Arts"},
  {id:"444d0472d7d94f569da6fd7a5608faba", itemName:"Sports"}
];

// Now they are actual key value pair
this.selectedItems = [
  {id:"abee232",itemName:"Attractions"},
  {id:"b6b1a23",itemName:"Artists"},
  {id:"08a58c8",itemName:"Performing Arts"},
  {id:"444d047",itemName:"Sports"}
];
&#13;
&#13;
&#13;

&#13;
&#13;
//CSV Format

private addRequestOptions(params: Args[]): RequestOptions {
  let options: RequestOptions = new RequestOptions();
  let list: string = "";
  options.params = new URLSearchParams();
  if (params != null) params.forEach((p: Args) => {
    list + p.id + ",";
  });
  options.params.set("collectionId", list);
  console.log(options);
  return options;
}

// Array of parameters format

private addRequestOptions(params: Args[]): RequestOptions {
  let options: RequestOptions = new RequestOptions();
  let list: string = "";
  options.params = new URLSearchParams();
  if (params != null) params.forEach((p: Args) => {
    options.params.append("collectionId", p.id);
  });
  console.log(options);
  return options;
}
&#13;
&#13;
&#13;

这将为您作为RequestOptions传递给它的参数创建一个agrs,您可以直接在Get方法中插入它。

&#13;
&#13;
this.http.get(url, this.addRequestOptions(this.selectedItems))
  .map((res: any) => res.json() as any)
  .catch((err: Response) Observable.throw(console.log(err)));
&#13;
&#13;
&#13;

&#13;
&#13;
import {Http, RequestOptions, URLSearchParams} from "@angular/http";
import "rxjs";
import {Observable} from "rxjs/Observable";
&#13;
&#13;
&#13;

<强>更新 现在,您应该能够将selectedItems变量作为addRequestOptions参数传递,它将为所有id生成url参数。

这篇文章显示了几种可以将值传递为Array of parameters

的方法