Angular 4 在 http post 请求后获取函数 return 值

Angular 4 get function return value afrer http post request

我创建了一个控制器方法,该方法在解决 reCaptcha 和请求 returns 验证码响应 JSON 后向 google 服务器发送验证码响应。控制器方法 returns true 如果验证码响应是 =="success",否则它 returns false

请求是通过 http POST 发送的,但我面临的问题是:在 POST 请求后收到响应后,如何从控制器方法中获取布尔值?

控制器方法:

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

在 chrome 调试中我得到一个 Observable:http://prntscr.com/ke5eeo

return response.json() as boolean returns 用于可观察对象,不适用于您的 checkRecaptcha 函数。你需要监听你自己的 checkRecaptcha 返回的 Observable:

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

您需要订阅 observable...

checkRecaptcha(url: string, data: Object): Observable<boolean> {
    this.timerService.resetTimer();
    return this.http.post(url, JSON.stringify(data), this.sharedService.getRequestHeaders());
}

之后您应该能够调用该服务并订阅其结果:

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