首页 > 解决方案 > .Subscribe() 函数接收值但无法进入函数块

问题描述

使用 rxjs observable 从前端调用 springboot 后端的服务。即使使用 .subscribe 函数调用此服务,它已成功返回一个值,我也无法进入订阅块,它直接到达块的末尾。

登录组件.ts

validate() {
    console.log('need to validate');
    this.loginService.checkLogin(this.userName, this.pwd).subscribe(resp => {
      console.log(resp);
      if (resp === 'success') {
        this.router.navigateByUrl('/home');
      }
    }, error => {
      this.toastr.error(error.error.message);
    });
  }

登录服务.ts

export class LoginServiceService {

  url = 'http://localhost:8089/login/check';
  constructor( private http: HttpClient) { }

   public checkLogin(userName, password): Observable <any> {
    let headersValue = new HttpHeaders();
    headersValue = headersValue.set('Access-Control-Allow-Origin', '*');
    headersValue = headersValue.set('Content-Type', 'application/json');
    headersValue = headersValue.set('userName', userName);
    headersValue = headersValue.set('password', password);
    return this.http.get<any[]>(this.url, { headers: headersValue });
}
}

预期结果:它应该进入订阅块并在控制台中显示 resp 并输入 if 块。

实际结果:只显示“需要验证”。

并在错误检查后直接到达块的末尾。

标签: typescriptspring-bootobservableangular7

解决方案


我认为您的问题可能与标题有关。我不确定您是否需要其中任何一个,但更具体地说,我认为用户名和密码根本不属于那里。他们可能应该是参数。我认为以下内容可能会对您有所帮助:

public checkLogin(userName, password): Observable <any> {
    let headersValue = new HttpHeaders();
    headersValue = headersValue.set('Access-Control-Allow-Origin', '*');
    headersValue = headersValue.set('Content-Type', 'application/json');
    const params = { userName, password };
    return this.http.get<any[]>(this.url, { headers: headersValue, params });
}

推荐阅读