-1

I have simple Angular Application witch get values from Spring-Boot backend

export class UserDto {

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

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

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

and than in my component i have function which create map of values:

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

When i use:

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

I have in console result:

enter image description here

the login from UserDto is crossed in red

I have Map(0) but in size it's 18... when i try get real size this map i have size = 0. I can see objects in "Entries" but I can't get them in any way.

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

How can I get a solution that I could map these objects, then how to find the password using the given key as login ????

mat373
  • 171
  • 4
  • 13
  • 1
    You might need to read up on the async nature of Observables. You are returning priceListMap before the the ons emits. – MikeOne Nov 19 '21 at 20:27

1 Answers1

0

The problem is here,

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

The code in the subscription is going to fire asynchronously so it is likely that you are returning priceListMap before its value is set.

There are a number of ways to handle this, the best one is to push priceListMap directly onto your template using the async pipe. You can also wait on the return value with an async/await pattern, but this can get a little messy in my opinion. You can take a look here to see how async/await works with observables as well.

David Kidwell
  • 600
  • 1
  • 6
  • 15