Object Promise is returned when accessing specific object attribute in an array of objects? (Angular - Ionic)

Viewed 46

I have an array of objects, I want to be able to mention a specific attribute within a single object within that array. What I have done so far is as follows:

I am storing my array of objects within Ionics storage. I then use an async function to assign the array of objects to an array in my typescript file: This can be seen here;

//The new array
users: User[] = [];

//The async function
async readUsers() {
    this.users = await this.service.readUsers();
    this.index = this.users.findIndex((x => x.id == this.passed_id));
    return this.users[this.index];
  }

The async function assigns the array to this.users, after which I then find the object i want and assign its index to this.index, which i then use to identify the desired object in the this.users array. Everything up until here works just fine, i manage to get the desired object within the stored array.

I am then able to read the attributes of the selected object using:

"alert(this.users[this.index].firstName)", instead of the last line in the async function. This works fine as well.

However, now i want to mention a specific object in a form builder control as follows:

firstName: [this.readUsers(), Validators.required],

This does not work, and all that is returned is [Object Promise]. What am i able to do here in order to read a specific attribute (as text) in the form input from the object array mentioned above? Any help is appreciated.

1 Answers

You have to await this.readUsers() for the unwrapped value.

async method() {
   ...
   firstName: [await this.readUsers(), Validators.required],
   ...
}

Maybe for you, you have to do something like this:

form: any; // using any, but you can change the type to what FormBuilder returns
....
async ngOnInit() {
  const users = await this.readusers();
  this.form = this.formBuilder.group({
     firstName: [users, Validators.required],
  });
}
Related