如何在角4中的后http中进行错误处理?

时间:2018-04-13 07:19:42

标签: angular http post angular-http

我试图在用户关闭窗口时进行此调用。

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

因为当用户关闭窗口时会调用此窗口,所以我不知道它是否成功发布。

发布后如何处理成功或错误?

目前,它没有提醒任何事情。

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

您可以通过以下方式处理错误:

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