angular6-在同一服务的响应回调中调用服务

时间:2018-07-11 04:02:00

标签: angular authentication mean-stack angular6

问题只是标题说的。当我在响应下第二次调用服务时,同一服务的回调显示this error

app.component.ts代码

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代码

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()));
        }
    }
}

服务功能注册中的想法是,当gethash参数为true时,API返回令牌以将其保存在localStorage中。

非常感谢您的帮助:)

PS1:我正在关注Udemy的this教程。 PS2:我试图声明一个var self = this,但是不起作用。

1 个答案:

答案 0 :(得分:0)

最后,我通过以下方式离开了代码:

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()));
        }
    }

感谢JB Nizet的建议。