angulartypescriptpostrecaptchadataservice

Angular 4 get function return value afrer http post request


I created a controller method that sends a captcha response to google server after solving a reCaptcha and the request returns a captcha response JSON. Controller method returns true if captcha response is =="success", else it returns false.

The request is sent with http POST, but the problem I'm facing is: how do I get the boolean value from controller method after receiving a resposne after POST request?

Controller method:

 {
        if(ModelState.IsValid)
        {
            bool success = false;

            var client = new System.Net.WebClient();

            string PrivateKey = "6LeiumYUAAAAAMS0kU0OYXaDK0BxHO7KJqx2zO7l";

            var GoogleReply = client.DownloadString(string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", PrivateKey, Model.RecaptchaResponse));

            var captchaResponse = Newtonsoft.Json.JsonConvert.DeserializeObject<ReCaptchaController>(GoogleReply);

            success = captchaResponse.Success.ToLower() == "true" ? true : false;

            return Ok(success);
        }

        return BadRequest();

    }

    [JsonProperty("success")]
    public string Success
    {
        get { return m_Success; }
        set { m_Success = value; }
    }

    private string m_Success;
    [JsonProperty("error-codes")]
    public List<string> ErrorCodes
    {
        get { return m_ErrorCodes; }
        set { m_ErrorCodes = value; }
    }

    private List<string> m_ErrorCodes;
}

POST request in DataService:

//Http Post request for server-side reCAPTCHA validation
checkRecaptcha(url: string, data: Object): Observable<boolean> {
    this.timerService.resetTimer();
    return this.http.post(url, JSON.stringify(data), this.sharedService.getRequestHeaders())
        .map((response: Response) => {
            return response.json() as boolean
        })
        .catch((response: Response) => {
            return Observable.throw(response);
        });
}

app.component.ts:

resolved(captchaResponse: string) {
    let data = {
        RecaptchaResponse: captchaResponse
    };
    let result = this.dataService.checkRecaptcha('api/recaptcha/validate', data);
    console.log(result);
}

In chrome debug I get an Observable: http://prntscr.com/ke5eeo


Solution

  • The line return response.json() as boolean returns for the observable, not for your checkRecaptcha function. You will need to listen to your own checkRecaptcha's returned Observable:

    this.dataService.checkRecaptcha('api/recaptcha/validate', data).subscribe(
      (result: boolean) => console.log(result)
    );