Communication serveur
import { bootstrap } from '@angular/platform-browser-dynamic';
import { HTTP_PROVIDERS } from '@angular/http';
import { AppComponent } from './app.component';
bootstrap(AppComponent, [ HTTP_PROVIDERS ]);
request() // [X] requête X, X étant un verbe HTTP
get() // [read] requête GET
post() // [create] requête POST
put() // [update/replace] requête PUT
delete() // [delete] requête DELETE
patch() // [update/modify] requête PATCH
head() // [head] requête HEAD
loadItems() {
return this._httpService.get(BASE_URL)
.map(res => res.json())
.toPromise();
}
createItem(item: Item) {
return this._httpService.post(BASE_URL, JSON.stringify(item), HEADER)
.map(res => res.json())
.toPromise();
}
updateItem(item: Item) {
return this._httpService.put(`${BASE_URL}${item.id}`, JSON.stringify(item), HEADER)
.map(res => res.json())
.toPromise();
}
deleteItem(item: Item) {
return this._httpService.delete(BASE_URL, HEADER)
.map(res => res.json())
.toPromise();
}
// Creation d'un observable
this._httpService.get('http://domain.com')
// Consommer un Observable
source.subscribe(
data => console.log(`Next: ${data}`),
err => console.log(`Error: ${err}`),
() => console.log('Completed')
);
// Creation d'un observable
this._httpService.get('http://domain.com')
.toPromise()
.then(res => res.json().data)
.then(users => this.users = users)
.catch(this.handleError)
// Creation d'un observable
this._httpService.get('http://domain.com')
.catch(error => {
console.log(`An error occurred ${error}`)
return Observable.throw(error.json().error || 'Server error')
})
let headers = new Headers({'Content-Type': 'application/json'})
let options = new RequestOptions({headers: headers})
this._httpService.post('users.json', '{}', options)