Search code examples
angular5angular-httpclient

HttpClient or Http POST with header request not hitting to the server


I'm trying to issue an http request to validate user and in response i need to get token issued by the server.

this ajax call working fine

$.ajax({
                url: '/token',
                'data': JSON.stringify({ Id: "test", Password: "test" }),
                'type': 'POST',
                'processData': false,
                'contentType': 'application/json',
                success: function (response) {
                    console.log("token =" + response);
                },
            });

But i need it in angular so i tried below two methods but none of them worked.

1st

let header = new Headers({ 'Content-Type': 'application/json', 'processData': false});
        let options = new RequestOptions({ headers: header });
        this.http.post('/token', JSON.stringify({ Id: "test", Password: "test" }), options)
            .map(response => {
                debugger;
                console.log("token =" + response);
            });

2nd

this.httpClient.post<any>("/token",
            { 'Id': "test", 'Password': "test" },
            {
                headers: new HttpHeaders({ 'Content-Type': 'application/json' }),
                observe: 'response'
            });

what is wrong with them.
I am using Dotnet Core 2.1 and angular 5
Please help me to solve this issue.


Solution

  • Your methods are observables.

    In order to send the request and get the result, you need to subscribe to them.

    This is an example of the 2nd method.

    this.httpClient.post<any>("/token",
                        { 'Id': "test", 'Password': "test" },
                        {
                            headers: new HttpHeaders({ 'Content-Type': 'application/json' })
                        }).subscribe(response => {
                               console.log("token =" + response);
                        });