How do I get API error response in CatchError block in Angular 6?

时间:2018-11-05 17:43:57

标签: angular angular6

I am new in angular and Angular 6. I have an API and whose 400 bad request error like

POST /register 
{
    "success": false,
    "error": {
        "email": [
            "Enter a valid email address."
        ]
    }
}

I am trying to call API in angular like below

register(username: string, email: string, password, first_name: string, last_name: string) {
        return this.http.post<any>(this.registerURL,
            {"username": username, "password": password, "email": email, "first_name": first_name,
                "last_name": last_name})
            .pipe(map(user => {
                    if (user && user.token) {
                        localStorage.setItem('token', user.token);
                    }
                    return user;
                }),
                catchError((error: any) => {
                    return throwError(error);
                })
            );
    }

My question is how do I get API error response in CatchError block.

1 个答案:

答案 0 :(得分:0)

您可以按照HttpClient文档中的说明,通过向HttpClient提供options对象来访问完整的响应。

this.http.get<any>(
this.configUrl, { observe: 'response' });

Blitzstack示例:https://stackblitz.com/edit/angular-lkxdwj?file=src%2Fapp%2Fhello.component.ts

带有标头和statusCode的响应将作为catchError运算符和订阅函数的错误回调的参数提供。