概要
- Angular で
HttpClient.get
メソッド使用時にURLクエリパラメータを配列で渡す場合のサンプルです。
実装方針
- HttpParams の生成時に fromObject で配列を指定する。
実行環境
使用ライブラリ
app.service.ts
import { HttpClient, HttpParams } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
@Injectable({
providedIn: 'root',
})
export class AppService {
constructor(private http: HttpClient) {}
get(...params: string[]): Observable<any> {
const url = `./assets/empty.json`;
const httpParams = new HttpParams({ fromObject: { p: params.filter((param) => param) } });
return this.http.get(url, { params: httpParams, observe: 'response' }).pipe(
tap((res) => {
console.log(`url: ${res.url}`);
}),
);
}
}
app.component.ts
import { Component } from '@angular/core';
import { AppService } from './app.service';
@Component({
selector: 'app-root',
template: `
<div>
<div><input type="text" [(ngModel)]="text1" /></div>
<div><input type="text" [(ngModel)]="text2" /></div>
<div><input type="text" [(ngModel)]="text3" /></div>
<button (click)="onClick()">get</button>
</div>
`,
})
export class AppComponent {
text1 = 'abc';
text2 = 'def';
text3 = 'hoge';
constructor(private appService: AppService) {}
onClick(): void {
this.appService.get(this.text1, this.text2, this.text3).subscribe();
}
}
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, HttpClientModule, FormsModule],
bootstrap: [AppComponent],
})
export class AppModule {}
実行結果
github.com