123Ex
123Ex

Reputation: 916

Angular2 response mapping with subscriber

In my angular2 application, I do have authentication.service.ts and login.component.ts

authentication.service.ts

login(username: string, password: string) {
    return this.http.post('/auth/loginapp', JSON.stringify({ username: username, password: password }))
      .map((response: Response) => {
        // login successful if there's a jwt token in the response
        let user = response.json();
        //Printt the backend response to the console
        this.logger.debug('User '+ JSON.stringify(user));
        if (user && user.token) {
          // store user details and jwt token in local storage to keep user logged in between page refreshes
          localStorage.setItem('currentUser', JSON.stringify(user));
        }
      });
  }

authentication.service.ts calls to backend authentication services and get the response according to user input and save to the localStorage.

login.component.ts

this.authenticationService.login(this.model.username, this.model.password)
      .subscribe(
        data => {
          this.logger.debug("Login User"+ JSON.stringify(data))
          this.router.navigate(['register']);
        },
        error => {
          this.logger.error(error);
          this.alertService.error(error);
          this.loading = false;
        });

I am always getting data as undefined in login.component.ts. authentication.service.ts gets the response correctly. I need to get the response data to the login.component.ts. could anyone tell me the issue with my code?

Upvotes: 0

Views: 75

Answers (1)

Thibs
Thibs

Reputation: 8258

The Observable map operator expect you to return something, and I believe you are not returning anything there. Usually you want to modify the data in a map operator. But in your case you are not. Since you performing an action outside the 'stream' one option is to use the .do operator.

You can use do instead...

.do((response: Response) => {
        let user = response.json();
        if (user && user.token) {
          localStorage.setItem('currentUser', JSON.stringify(user));
        }
});

If you insist on using map, make sure it returns something...

.map((response: Response) => {

        let user = response.json();
        if (user && user.token) {
          localStorage.setItem('currentUser', JSON.stringify(user));
        }
       return response;
});

Upvotes: 2

Related Questions