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通信
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 parameters = { title: 'Ionic POST Request Example' };
this.http.post('https://example.com', { headers, parameters }).subscribe(data => {
console.log(data);
});
}
}