2017-05-25 8 views
0

私は私のAPIには、このような要求を取得送信する必要があります。動的に形成されたHTTPリクエスト

http://test.example.com/api/activity/search?word={word}&age={age}&free={free} 

、その後* ngForと私のページにこの活動を示すが、ユーザーが入力を埋めるとき、私は動的に値を挿入する必要がありますこの不必要な議論の中で。 は、私はまだ行って何を:

//activity.service.ts : 
    searchActivities(word?: any, age?: any, free?: any) { 
    let w, a, f; 
//contat values from forms here 
    w = word  ? `word=${word}` : ''; 
    a = age  ? `age=${age}` : ''; 
    f = free  ? `free=${free}` : ''; 

    return this.http.get(`http://test.example.com/api/activity/search?${w}${a}${f}`); 
} 

あなたが気づいたように、私はここにアンパサンドを欠場し、ユーザーは、彼がすることはできません、すべて無料のサッカーの活動を見たいときには、例えば、一つだけの入力で動作します。入力の

activities = []; 
args: any[] = [null, null, null]; //array for values 
//funtction attached to input's events 
setArgument(index, value) { 
     this.args[index] = value; //fills array with values from inputs 
     this.activityService 
    // spread operator gives error in typescript for some reason, so i decided to put arguments this way 
     .searchActivities(this.args[0], this.args[1], this.args[2]) 
     .subscribe((data: Response) => this.activities = data.json()); 
    } 

例:私のコンポーネントで

私はこれ持って、私はあなたが私が何をしようとしている理解を願ってい

<md-checkbox (click)="setArgument(5, !IsFree)" [(ngModel)]="IsFree" name="free">Free</md-checkbox> 
<md-input-container> 
    <input (focusout)="setArgument(0, word)" [(ngModel)]="word" name="word" mdInput placeholder="Search word"> 
</md-input-container> 

を、私はプログラミングの初心者だと多分私それは完全に悪い方法を行う。私はアンパサンドに対処する方法をアドバイスしてください、そして多分あなたのアンパサンドの問題に良い解決策は、あなたが次のようなコードを追加することができますArray.prototype.join

だろう何とか

+1

https://angular.io/docs/ts/latest/guide/server-communication.html#!#search-parameters(もちろん、これはJsonpサービスだけでなく、Httpサービスにも有効です) 。 –

+0

ありがとう、それは私が探していたものですが、このひどいコードを見つけられずに書き始めました。 –

答えて

0

このコードを簡素化または書き換え:

w = word  ? `word=${word}` : ''; 
a = age  ? `age=${age}` : ''; 
f = free  ? `free=${free}` : ''; 

q = [w, a, f].filter(function(x) { return x !== '' }).join('&'); 

return this.http.get(`http://test.example.com/api/activity/search?${q}`); 

したがって、すべてのクエリ文字列が含まれている配列を作成します。filterは空で、結合はアンパサンド文字で区切られた文字列にまとめられます。

+0

助けてくれた!ありがとう:) –

関連する問題