【问题标题】:Angular - How to get an object map from httpClient and return it in a methodAngular - 如何从 httpClient 获取对象映射并在方法中返回它
【发布时间】:2021-12-30 12:48:30
【问题描述】:

我有一个简单的 Angular 应用程序女巫从 Spring-Boot 后端获取值

export class UserDto {

  constructor(
    public login: string,
    public password: string,
  ) {
  }
}

export class AuthService {
   private url = '....';

getUser() {
   return this.http.get<UserDto[]>(this.url);
  }
}

在我的组件中,我有创建值映射的函数:

constructor(private auth: AuthService){}

private getMapOfUsers() {
    const priceListMap: Map<string, string> = new Map<string, string>();
    this.auth.getUser().subscribe(res => {
      res.map(item => {
          priceListMap.set(item.login, item.password);
        }
      );
    });
    return priceListMap;
  }

当我使用时:

getLoginData() {
    console.log(this.getMapOfUsers());
  }

我有控制台结果:

来自 UserDto 的登录以红色划线

我有Map(0),但大小为 18...当我尝试获取实际大小时,此地图的大小 = 0。我可以在“条目”中看到对象,但我无法以任何方式获取它们。

getLoginData() {
    console.log(this.getMapOfUsers().size);  // result = 0
  }

如何获得可以映射这些对象的解决方案,然后如何使用给定密钥作为登录名找到密码????

【问题讨论】:

  • 您可能需要阅读 Observables 的异步特性。您在 ons 发出之前返回 priceListMap。

标签: angular typescript


【解决方案1】:

问题来了,

private getMapOfUsers() {
    const priceListMap: Map<string, string> = new Map<string, string>();
    this.auth.getUser().subscribe(res => {
      res.map(item => {
          priceListMap.set(item.login, item.password);
        }
      );
    });
    return priceListMap;
  }

订阅中的代码将异步触发,因此您很可能在设置其值之前返回 priceListMap。

有很多方法可以解决这个问题,最好的方法是使用 async 管道将 priceListMap 直接推送到您的模板上。您也可以使用async/await 模式等待返回值,但在我看来这可能会有点混乱。您可以查看 here 以了解 async/await 如何与可观察对象一起工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-06
    • 2019-10-16
    • 2013-05-31
    • 1970-01-01
    • 2019-07-06
    • 2018-07-25
    • 2018-12-14
    • 2018-05-30
    相关资源
    最近更新 更多