discCard
discCard

Reputation: 521

Return reponse from http post Angular

I would like to take a reponse from post metho and use this value in subscribe method. In comments I wrote also information about my question.

My code

login(): void {
    this.authService.login(this.model)
      .subscribe(next => {
          //here I wanted to use received value
          this.alertifyService.success('success');
        }, error => {
          this.alertifyService.error('error');
        }
      );
  }

and

  login(model: any) {
    return this.http.post(this.baseUrl + 'login', model)
      .pipe(map((response: any) => {
          // how to send this reponse to my subscribe method ?
          const user = response;
          if (user) {
            localStorage.setItem('token', user.token);
            this.decodedToken = this.jwtHelper.decodeToken(user.token);
            console.log(this.decodedToken);
          }

        }
      ));
  }

Upvotes: 2

Views: 371

Answers (1)

Michel Vorwieger
Michel Vorwieger

Reputation: 722

you just have to return the value from map

login(model: any) {
        return this.http.post(this.baseUrl + 'login', model)
            .pipe(map((response: any) => {
                    const user = response;
                    if (user) {
                        localStorage.setItem('token', user.token);
                        this.decodedToken = this.jwtHelper.decodeToken(user.token);
                        return this.decodedToken;
                    }
                }
            ));
}

and then use it like this:

authService.login(/**/).subscribe(token => /*do something with the token*/)

Upvotes: 3

Related Questions