I am new to Angular2. I have referred the Hero Tutorial given in official web site and have written the following code for HTTP post request in Angular2 as per my requirement. I am used to java-script and i use AJAX calls to interact with web server, in javascript-AJAX call we can perform some function on successful AJAX call(callback function). How do i achieve that in angular2 ? i want to use Alerts also. On success/fail of each call show a Alert Box saying its Success or Failure.
@Injectable()
export class LicenceService {
constructor(private http: Http) {}
private headers = new Headers({'Content-Type': 'application/json'});
/* URL to web api*/
private licenceUrl = 'http://localhost:5000/***/****/installation/uploadLicense';
sendData(key: string){
return this.http
.post(this.licenceUrl, key, this.headers)
.toPromise()
.then(res => res.json().data)
.catch(this.handleError);
}
private static handleError (error: any) {
console.log(error);
return Promise.reject(error.json());
}
All you need is already in your code
sendData(key: string){
return this.http
.post(this.licenceUrl, key, this.headers)
.toPromise()
.then(res => {
res.json().data;
// code here is executed on success
})
.catch(this.handleError);
}
or for the caller
this.sendData(somekey).then(result => /*put after after success code here */);