Quantcast
Channel: ASP.NET Core
Viewing all articles
Browse latest Browse all 9386

Get Error value from Web Api to Angular as Typescript

$
0
0

Hi Folks,

I am using Asp.net core RC2 Web Api service with angular 2.
here is my sample real code:
AccountController.cs

        [HttpPost("register")]
        public async Task<IActionResult> Register([FromBody] RegisterViewModel model)
        {
           ..........
                if (result.Succeeded)
                {
                    // Create Role
                    ......................

                    // Create Token
                    string token = CreateTokenRegister(model);
                    string response = "{\"id_token\": \"" + token + "\"}";
                    return Ok(response);
                }
                else
                {return GetErrorResult(result);
                }
            }

            return Ok();
        }

        //Helper
        private IActionResult GetErrorResult(IdentityResult result)
        {
            foreach (var error in result.Errors)
            {
                ModelState.AddModelError(string.Empty, error.Description);
            }
            return Ok();
        }

Signup.ts

    signup(event, username, password) {
        let body = { Role: this.roleName, Username: username, Password: password };

        this.authService.postRegister(body)
            .subscribe(response => {
                localStorage.setItem('jwt', response.id_token);
                localStorage.setItem('current_user', username);
                this.getRoleByUser(username);
                this.router.parent.navigateByUrl('/home');
            },
            error => {<<<<<<e.g Username is already taken or exists. etc
                this.errorMessage = <any>error;
                alert(this.errorMessage);
            }
            //error => alert(error)   
            //error => {
            //    alert(error.text());
            //    console.log(error.text());
            //}
        );
    }

Service.ts

    postRegister(registerBody: any) {
        let url = window.location.origin + '/api/account/register';
        let body = JSON.stringify(registerBody);

        return this.http.post(url, body, { headers: contentHeaders })
            .map((res: Response) => res.json())
            .do(data => console.log(data))
            .catch(this.handleError);
    }

    private handleError(error: Response) {
        console.error(error);
        return Observable.throw(error.json().error || 'Server error');
    }

I want to show an error message value from server as Web Api. E.g Username is already taken or exists. etc
How to get an error message value from Web api controller?
I am waiting for your response.
Thanks in Advance!


Viewing all articles
Browse latest Browse all 9386

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>