3

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());
}

2 Answers 2

4

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 */);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you.It was very helpful. I went in detail and read the Angular docs again and got my doubts clear. Services and HTTP section solved my problem.
2

Although, Your question is already answered, Here is another approach which keeps Sevice and callback logic separate. I have achieved it with the use of subscibe and Observable

Here is my question.compnent.ts

    ngOnInit() {
               this.getQuestions();
    }        
    getQuestions() {
        this.yourService.getQuestions()
            .subscribe(
            data => this.displayData = data,
            error => this.errorMessage = <any>error,
            () => { 
                  //this gets called on completion, callback code comes here
                  } 
            );
    } 

And my question.service.ts which takes care of HTTP requests part

   getQuestions(): Observable<DisplayData[]>{
      const endPoint = 'http://localhost:3000/yourApi';
      return this.http.get(endPoint).map((response: Response) => response.json());
}

Note: this.displayData is a variable of type DisplayData[], which is used as an observable in Service.

Sorry for the long post. Cheers :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.