2.9 KiB
2.9 KiB
Http & Backend interaction
Structure
Element | Description |
---|---|
http Verb | GET, PUT, DELETE, POST, ... |
ULR | API Endpoint, domain.tld/user/1 |
Headers | Metadata {"Content-Type": "application/json"} |
Body | Payload |
Setup
Add dependencies in app.module.ts
import { HttpClientModule } from '@angular/common/http';
@ngModule({
imports: [ HttpClientModule ]
})
POST
POST-Request
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
loadedPosts = [];
// inject the service
constructor(private http: HttpClient) {}
ngOnInit() {}
onCreatePost(postData: { title: string; content: string }) {
// Send Http request
this.http
.post(
'https://ng-complete-guide-c56d3.firebaseio.com/posts.json',
postData
)
.subscribe(responseData => {
console.log(responseData);
});
}
}
POST returns an observable which the function has to be subscribed to. If no one is interested in the result, the POST-request will not be sent.
GET
GET-Request
private fetchPost() {
// Send Http request
this.http
.get(
'https://ng-complete-guide-c56d3.firebaseio.com/posts.json'
)
.subscribe(posts => {
console.log(posts);
});
}
DELETE
DELETE-Request
private fetchPost() {
// Send Http request
this.http.delte('https://ng-complete-guide-c56d3.firebaseio.com/posts.json')
.subscribe(doSomething);
}
Errorhandling
Errorhandling on a GET-Request
private fetchPost() {
// Send Http request
this.http
.get(
'https://ng-complete-guide-c56d3.firebaseio.com/posts.json'
)
.subscribe(posts => {
console.log(posts);
}, error => {
this.error = error.message;
console.log(error);
});
}
catchError / throwError
.subscribe(posts => {
console.log(posts);
}, error => {
catchError(errorRes => {
return throwError(errorRes);
})
});
Headers
Cofigurate the request with headers
this.http
.get(
'https://ng-complete-guide-c56d3.firebaseio.com/posts.json',
{
headers: new HttpHeaders( {
'key': 'value'
})
}
)
Query Params
Adding query Params
this.http
.get(
'https://ng-complete-guide-c56d3.firebaseio.com/posts.json',
{
headers: new HttpHeaders( {
'key': 'value'
}),
params: new HttpParams().set('customerId', '69')
}
)
Will result to the URL like: https://ng-complete-guide-c56d3.firebaseio.com/posts.json?customerId=69