Some questions are also provided in the code comments.
code:
import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class Reviews {
data: any;
constructor(public http: Http) {
this.data = null;
}
getReviews(){
if (this.data) {
return Promise.resolve(this.data);//what is the use of this promise here?
}
return new Promise(resolve => {
this.http.get('http://localhost:8080/api/reviews')
.map(res => res.json()) //do we use .map operator in observables only? also the subscribe function? do we not use here .then?
.subscribe(data => {
this.data = data;
resolve(this.data);
});
});
}
createReview(review){
let headers = new Headers(); // what is the use of headers here?When do we use these headers?
headers.append('Content-Type', 'application/json');
this.http.post('http://localhost:8080/api/reviews', JSON.stringify(review), {headers: headers})
.subscribe(res => {
console.log(res.json());
});
}
I read this tutorial there I found this code.please help me out.This is the Service class that is used here in the code.And when can we use Observables and promises?
For references and understandings I have read the stack answers of a post.