【问题标题】:Subscribe Observable<Type>订阅 Observable<Type>
【发布时间】:2018-08-28 23:27:28
【问题描述】:

订阅 Observable:

checkAllowEmail(control: FormControl) {
    this.userService.getUserByEmail(control.value)
     .subscribe((user: UserDto) => {
       console.log(user);
       if (user !== undefined) {
         console.log(this.isAllowEmail);
         this.isAllowEmail = false;
         console.log(this.isAllowEmail);
       }
     });
  }

从方法返回 Observable:

getUserByEmail(email: string): Observable<UserDto> {
    return this.http.get(`http://localhost:9092/api/v1/users?email=${email}`)
      .map((response: Response) => response.json())
      .map((user: UserDto) => user ? user : undefined);
  }

类 UserDto:

export class UserDto {
  constructor(
    public email: string,
    public name: string,
    public role: string
  ) {}
}

BE方回应:

{"name":"art","email":"art@mail.ru","role":"user"}

为什么我可以在 checkAllowEmail 方法的 if 语句中将变量 isAllowEmail 更改为 false?

【问题讨论】:

  • 你能看到那两个console.logs吗?
  • 这是什么:console.log(user); log?
  • @standby954 不,什么都没有
  • @Ferus7 检查用户对象
  • 然后,正如我所说,要么你没有从服务器接收数据,要么你应用到 observable 的运算符之一出现问题。考虑调试或在subscribe函数中添加错误回调,以了解某处是否有错误

标签: javascript angular typescript rxjs observable


【解决方案1】:

我认为在使用 HttpClient 时(从 Angular 版本 4 开始),您仍然不必使用 map 功能。尝试使用

getUserByEmail(email: string): Observable<UserDto> {
    return this.http.get<UserDto>(`http://localhost:9092/api/v1/users?email=${email}`);
}

还可以使用 Postman 之类的工具,甚至使用控制台中的 curl 来验证您的 api 返回正确/预期的响应。

还要检查你是否使用'use strict';在这种情况下,this 将引用您传递给 subscribe 方法的可调用对象,而不是周围的组件类。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-29
    • 1970-01-01
    • 2023-04-02
    • 2017-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多