【问题标题】:Angular HttpClient get request no return in subscribeAngular HttpClient获取请求在订阅中没有返回
【发布时间】:2020-06-03 11:07:25
【问题描述】:

我想实现一个登录。因此,我发出了获取用户信息并将其写入本地存储的 get 请求,但不知何故,它永远不会到达我想调用 setItem 的地步。

AuthenticationService.ts

export class AuthenticationService {
  constructor(private http: HttpClient) {}

  login(username, password) {
    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json',
        Authorization: 'Basic ' + btoa('' + username + ':' + password + ''),
      }),
    };
    this.http.get('api/user/loginInfo', httpOptions).subscribe((res) => {
      localStorage.setItem('currentUser', JSON.stringify(res));
    });
  }
}

login.component.ts

export class LoginComponent implements OnInit {
  constructor(private authService: AuthenticationService) {}

  ngOnInit(): void {}

  login() {
    const username = (document.getElementById('username') as HTMLInputElement)
      .value;
    const password = (document.getElementById('password') as HTMLInputElement)
      .value;
    this.authService.login(username, password);
  }
}

【问题讨论】:

  • login(username, password) 曾经被调用过吗?如果是这样:您是否在开发控制台中看到了请求(例如,在使用 Chrome 的开发者工具中)?请求成功,还是报错?
  • 是的,如果我在获取请求所在的行上设置断点,一切正常。编辑:是的,在开发控制台中没什么可看的。
  • 如果你设置了一个断点,那么功能就可以按预期工作,而没有断点不是吗?还是我错过了您评论的重点?
  • 是的,有断点它可以工作,没有。
  • 这似乎不对,因为断点不应该修改代码的行为。你是如何确保没有断点的键/值对没有设置的?

标签: angular typescript httpclient


【解决方案1】:

我犯了一个愚蠢的错误。我从表单中调用了方法,但不知何故存在问题。我现在已经删除了 html 中的表单标签,现在一切正常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-15
    • 2019-12-12
    • 1970-01-01
    • 2017-11-03
    • 2021-02-25
    • 2018-04-24
    • 1970-01-01
    • 2020-06-23
    相关资源
    最近更新 更多