Reckonsys
Reckonsys

Reputation: 361

How to render output according to response of post request made using Angular2

Currently I have a pop up for login so when the users enters the email id and password and make a server call. How do I react according to the response received. Earlier when I was using javascript I did it in the following manner:

submitHandler: function(form) {
        $('.signin_form').attr('disabled','disabled')

        var data = {}
        $(form).serializeArray().map(function(x){data[x.name] = x.value;});
        helperMethods.ajaxHandler(accounts_url+'login_user/','POST',
        data,authHelpers.afterLogin)
   }

On doing that this was being called:

var authHelpers = {    
    afterLogin : function(response){
    $('.signin_form').removeAttr('disabled')

    if(response.message!=undefined){
        if(typeof response.message.validation!='undefined'
         && response.message.validation.indexOf('verifi')!='-1'){
             $('.error_display').html('<div>Error</div>')

        }else{
            $('.error_display').text(response.message.validation)

        }
        $('input[name="password"]').val('')
        return;
    }
    if(response.token!=''){
       localStorage.setItem('jwt_token',response.token)
       window.location.reload()
    }

}
}

How can I implement the same using angular2 and Typescript?

Thank you.

Upvotes: 0

Views: 63

Answers (1)

Picci
Picci

Reputation: 17762

You need to use Angular2 http client to issue the POST request and the Observable subscribe method to elaborate the response.

Here an example of service class issuing the POST command

import {Injectable} from 'angular2/core';
import {Http, Headers, RequestOptions, Response} from 'angular2/http';
import {Environment} from '../settings/environment.service';
import {BackEndService} from '../app/backEnd.service';

@Injectable()
export class BackEndRestService extends BackEndService {

    constructor(private _http: Http, private _environment: Environment) {
        super();
    }

    authorize(inAccessCode: string) {
        let myUrl = this._environment.baseRestServicesUrl + 'authorize';
        let options = this.getOpionsForPost();
        let jsonString = JSON.stringify({_accessCode: inAccessCode});
        return this._http.post(myUrl, jsonString, options)
                                .catch(this.handleError)
    }

private handleError (error: Response) {
    return Observable.throw(errorText || 'Server error');
}

    private getOpionsForPost() {
        let headers = new Headers();
        headers.append('Content-Type', 'application/json');
        return new RequestOptions({headers: headers});
    }
}

Here is the code that calls the service

this._backEndService.authorize(this._user.accessCode)
                .subscribe(
                    data => {
                        let retJson = data.json();
                        if (retJson.code == 'OK') {  // do stuff
                            } else {
                                // manage the situation when the server responds KO
                    },
                    err => {
                        // manage errors;
                    },
                    () => console.log('Authorization Complete')
                );

I hope this helps

Upvotes: 1

Related Questions