I’ve noticed that while setting up a project, as described in my previous post, works as expected if you start from scratch. Starting from the github repo of my sample, sometimes you keep getting a 401 unauthorized on the post request.
If that’s the case, you can easily solve this by selecting the web api project in visual studio and open up the properties. Make sure to set Anonymous Authentication to Enabled.

Setting up our Angular application

I’m using the angular-cli. If you don’t know how to use it, check out their getting started information before continuing.

After setting up the application, we include the new HttpClientModule in the app.module:

Note: take special note of the fact that I’m using the new http import from @angular/common/http and not the old(er) one from @angular/http which still exists and works as before. I want to make use of newer functionality so I’m going for the new http implementation.

Note:the new http client uses json by default. And tries to parse what is returned by a request as json. In our sample web api we return a string, so we need to specify another responseType. Which in our case will be text. More about this can be found here.

The request (response) object needs to be immutable, so we need to clone the original request before we return it. We set the withCredentials parameter to true so that every outgoing request adds those credentials.

Lastly, we need to make sure that this interceptor is being used. So we need to register it in the app module.