angular6 - call a service in response callback of same service

The problem is just title says. When I call a service for second time under response callback of the same service shows this error.

app.component.ts code:

import { Component, OnInit } from '@angular/core';
import { User } from './models/user';
import { UserService } from './services/user.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  providers: [ UserService ]
})
export class AppComponent implements OnInit{
  public pageTitle = 'Portal de producción científica';
  public user: User;
  public identity;
  public token;
  public errorMessage;

  constructor(
    private _userService: UserService
  ){
    this.user = new User('', '', '', '', '', '', '','ROLE_ACADEMIC','','','','');
  }

  /**
   * ngOnInit
   */
  public ngOnInit() {}

  /**
   * onSubmit
   */
  public onSubmit() {
    this._userService.signup(this.user).subscribe(
      response => {
        let identity = response.user;
        this.identity = identity;
        if(!this.identity._id){
          alert("EL usuario no esta correctamente logeado.");
        } else{
          console.log(this);
          this._userService.signup(this.user, 'true').subscribe(
            response => {
              let token = response.token;
              this.token = token;
              if (this.token.length <= 0) {
                alert("EL token no se ha generado.");
              } else {
                console.log(token);
                console.log(identity);
              }
            },
            error => {
              var errorMessage = <any>error;
              if (errorMessage != null) {
                var body = JSON.parse(error._body);
                this.errorMessage = body.message;
                console.log(errorMessage);
              }
            }
          );
        }
      },
      error => {
        var errorMessage = <any>error;
        if(errorMessage != null){
          var body = JSON.parse(error._body);
          this.errorMessage = body.message;
          console.log(errorMessage);
        }
      }
    );
  }
}

user.service.ts code:

import { Injectable } from '@angular/core';
import { Http, Response, Headers } from '@angular/http';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs/Observable'; 
import { GLOBAL } from './global';

@Injectable()
export class UserService {
    public url: String;

    constructor(private _http: Http) {
        this.url = GLOBAL.url;
    }

    /**
     * signup
     */
    public signup(user_to_login, gethash = null) {
        if (gethash != null) {
            user_to_login.gethash = gethash;
        } else {
            let json = JSON.stringify(user_to_login);
            let params = json;

            let headers = new Headers({ 'Content-Type': 'application/json' });

            return this._http.post(this.url + 'login', params, { headers: headers }).pipe(map(res => res.json()));
        }
    }
}

The idea in the service function signup is when gethash parameter is true, API returns token for save it in localStorage.

Any help is greatly appreciated :)

PS1: I'm following this tutorial of Udemy. PS2: I tried to declare a var self = this, but doesn't work.

1 answer

  • answered 2018-07-12 01:04 Francisca GV

    Finally I left the code in the following way:

    app.component.html:

    public onSubmit() {    
        this._userService.signup(this.user).subscribe(
          response => {
            let identity = response.user;
            this.identity = identity;
    
            if(!this.identity._id){
              alert("EL usuario no esta correctamente logeado.");
            } else{
              this._userService.signup(this.user, 'true').subscribe(
                response => {
                  let token = response.token;
                  this.token = token;
    
                  if (this.token.length <= 0) {
                    alert("EL token no se ha generado.");
                  } else {
                    console.log(this.token);
                    console.log(this.identity);
                  }
                },
                error => {
                  var errorMessage = <any>error;
                  if (errorMessage != null) {
                    var body = JSON.parse(error._body);
                    this.errorMessage = body.message;
                    console.log(errorMessage);
                  }
                }
              );
            }
          },
          error => {
            var errorMessage = <any>error;
            if(errorMessage != null){
              var body = JSON.parse(error._body);
              this.errorMessage = body.message;
              console.log(errorMessage);
            }
          }
        );
      }
    

    user.service.ts:

    public signup(user_to_login, gethash = null) {
            if (gethash != null) {
                user_to_login.getHash = gethash;
                let json = JSON.stringify(user_to_login);
                let params = json;
                let headers = new Headers({ 'Content-Type': 'application/json' });
    
                return this._http.post(this.url + 'login', params, { headers: headers }).pipe(map(res => res.json()));
            } else {
                let json = JSON.stringify(user_to_login);
                let params = json;
    
                let headers = new Headers({ 'Content-Type': 'application/json' });
    
                return this._http.post(this.url + 'login', params, { headers: headers }).pipe(map(res => res.json()));
            }
        }
    

    Thanks to JB Nizet for the suggestion.