1

I'm having trouble while making a simple call from my NG app to my ASP.NET Core WebAPI. The code is the one following:

  this.http.post(actionUrl, credentialsDto)
  .map((data: Response) => {
    if (data !== null) {
      localStorage.setItem(this.tokenStorageKey, JSON.stringify(data));
    }
});

I tried to log my "data" callback parameter, but adding a call to console.log() in my if statement results in nothing (means i have no console output at all). Meanwhile if i add a console.log() call before or after the call, but in the same function, they are perfectly executed.

Does anyone know what's happening here? I'm a JS novice, so don't blame me. I'm using the HTTP client native in Angular 5.

Thanks in advance.

1 Answer 1

8

You need also to subscribe to the Observable. Observable will not fire if you haven't subscribed to it.

this.http.post(actionUrl, credentialsDto)
         .map((data: Response) => {
               if (data !== null) {
                  localStorage.setItem(this.tokenStorageKey, JSON.stringify(data));
               }

               return response;
          }).subscribe(response => /* something here */).

Starting from RxJS 5.5 you can't use map operator like you did. You need to use it inside pipe function.

RxJS 5.5 and higher approach

this.http.post(actionUrl, credentialsDto)
         .pipe(map((data: Response) => {
               if (data !== null) {
                  localStorage.setItem(this.tokenStorageKey, JSON.stringify(data));
               }

               return response;
          })).subscribe(response => /* something here */).
Sign up to request clarification or add additional context in comments.

10 Comments

With this approach, should I do my localstorage stuff in the subscribe or in the map function? Does it make sense to simply replace my map with the subscribe?
It depends on your logic. If you don't change response, you can replace map with tap.
Essentially my logic is to store the token received from the server in the localstorage. That's it.
So look at the tap operator if you use higher than 5.5, else look at do operator
Sorry but the version i'm using is 5.5.7 and there is not "tap" operator. Online i found that is available only for v6 or higher. Also the "do" is not working as well. Should i also use the "subscribe" at the end as you did?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.