I need to retrieve an array of user objects from a non-observable array of usernames (string[]). I am looking for a method that can fetch each user object through getUser(username) (HTTP GET request from Angular in-memory web API) for each provided username string, and then ultimately return an observable array of user objects. However, I am facing challenges figuring this out despite trying different approaches.
My preference is to avoid using promises if possible.
Here is the current method attempted:
usernamesToUserObjects(usernames: string[]): User[] {
var members: User[] = [];
for (let username of usernames) {
if (username.trim() === '') {
continue;
} else {
this.userService.getUser(username.trim())
.pipe(
map((user: User[] | undefined) => {
if (user !== undefined) {
console.log(`(debug) ${user.username} was found!`);
members.push(user);
}
})
);
}
}
// I acknowledge that the requests are not completing before moving on to the next one, but I need assistance in resolving this issue
console.log(`(debug) User objects are : ${members}`);
return members;
}
UserService methods in use: (functioning correctly)
usersUrl = '/api/users';
constructor(private http: HttpClient) {}
// fetching users in this manner in order to retrieve them from the Angular web api (can only be retrieved by 'id' and not by 'username')
users = this.http
.get<IUser[]>(this.usersUrl)
.pipe(retry(2), catchError(this.handleError('getUsers()', [])));
// check if user exists in the list of users
getUser(username: string): Observable<IUser | undefined> {
return this.users.pipe(
take(1),
map((users: IUser[]) => {
return users.find((user) => user.username === username);
})
);
}
How can I return an Observable<User[]>
and then extract User[]
from that observable?