AngularでバックエンドAPIへアクセスしてデータを取得する際、認証情報やクエリパラメータを付与したい時がある。
Post通信
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({ selector: 'app', templateUrl: 'app.component.html' })
export class AppComponent implements OnInit {
postId;
constructor(private http: HttpClient) { }
ngOnInit() {
const headers = { 'Authorization': 'Bearer my-token', 'My-Custom-Header': 'foobar' };
const body = { title: 'Ionic POST Request Example' };
this.http.post('https://example.com', body, { headers }).subscribe(data => {
console.log(data);
});
}
}
Get通信
まず、app.module.tsでModuleをImportする。
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';
import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';
@NgModule({
declarations: [AppComponent],
imports: [HttpClientModule,BrowserModule, IonicModule.forRoot(), AppRoutingModule],
providers: [{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy }],
bootstrap: [AppComponent],
})
export class AppModule {}
次に、下記のように書き換える。
import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpParams, HttpHeaders} from '@angular/common/http';
import { Logs } from 'selenium-webdriver';
@Component({
selector: 'app-tab1',
templateUrl: 'tab1.page.html',
styleUrls: ['tab1.page.scss']
})
export class Tab1Page implements OnInit {
val: string;
constructor(private http: HttpClient) { }
ngOnInit() {
const headers = new HttpHeaders()
.set("Id", "id_**********")
.set("Authorization", "token_**********");
const params = new HttpParams()
.set('query1', 'query1')
.set('query2', 'query2');
console.log('hi here');
this.http.get(
'http://*******.n*******.com/',
{headers,params,responseType: 'text'}
).subscribe(result =>{
console.log('result');
this.val = result;
})
}
}