如何在angular 4 中的post http 中进行错误处理?

How to do error handling in post http in angular 4?

我正在尝试在用户关闭 window 时进行此 post 调用。

createCallRecord (data) {
        let logData = {"chathist" : data , "uid": "1111" };
        let headers = new HttpHeaders();
        headers = headers.set("Content-Type", "application/json");
        let options = { headers: headers };
        return this.http.post(MY_URL, logData, options).subscribe(res => alert(res));
}

因为是在用户关闭window的时候调用的,不知道是不是post成功了。

posting后如何处理成功或错误?

目前,它没有发出任何警报。

如有任何帮助,我们将不胜感激!

您可以这样处理错误:

createCallRecord (data) {
    let logData = {"chathist" : data , "uid": "1111" };
    let headers = new HttpHeaders();
    headers = headers.set("Content-Type", "application/json");
    let options = { headers: headers };
    return this.http.post(MY_URL, logData, options)
        .subscribe(result =>
        {
          let value = result.json();
          console.log(JSON.stringify(value));
        }, err => { console.log(err); });

另一种选择是以这种方式使用处理函数:

createCallRecord (data) {
    let logData = {"chathist" : data , "uid": "1111" };
    let headers = new HttpHeaders();
    headers = headers.set("Content-Type", "application/json");
    let options = { headers: headers };
    return this.http.post(MY_URL, logData, options)
        .subscribe(res => this.resultHadler(res), err => this.errorHandler(err));
}

private resultHadler(res: any)
{
    let value = res.json();
    console.log(JSON.stringify(value));
}

private errorHandler(err: any)
{
    console.log(err);
}