2017-07-24 65 views
0

我有一個名爲selectedItems的數組,它是從多選下拉按鈕中填充的。 SelectedItems可能看起來像這樣如果選擇了所有選項:動態URL參數基於陣列中的id數Angular 2

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; 
} 

眼下這將創建一個擁有它的值作爲一個數組,但我的HTTP請求requestOptions對象並不在查詢字符串顯示此網絡選項卡中的參數字段。似乎addRequestOptions()工作正常,但沒有正確應用於獲取請求。目標是最終得到一個像這樣的URL:

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

我被卡住瞭如何做到這一點。任何幫助/提示/建議將不勝感激。

UPDATE W /最終代碼 我的問題是與我已經硬編碼'http://address/cards/topbrands?perPage=25'?perPage = 25被讀爲PARAMS(理應如此),因此除了對IDS因爲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) 
    } 

隨着我的函數調用傳遞SearchItems作爲參數,這個HTTP請求的功能。非常感謝@Praveen M的幫助和@ Jota.Toledo的解決方案!

回答

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

通過給它一個類型更新現有的數據數組,以便處理數組時有較小的擺動空間。

// 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"} 
 
];

//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; 
 
}

這將爲你作爲agrs它通過paramenters一個RequestOptions,你可以將它直接在Get方法。

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

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

UPDATE 現在,你應該能夠在傳遞selectedItems變量作爲addRequestOptions參數,它會產生網址parameres爲全id s。

這篇文章顯示了你幾個方法可以傳遞的值作爲Array of parameters

+0

這應該產生像'HTTP://地址/卡/ topbrand perpage = 25collectionId = ID1,ID2,ID2,ID4 ... ..' –

+0

很多後端框架都支持將key = value1&key = value2解析成一個沒有額外代碼的數組。通過使用昏迷方法,您需要創建一個解析器方法。 –

+0

@ Jota.Toledo感謝您指出,我不知道我是否應該使用該方法。我已經用兩個選項更新了代碼 –