-2

When I use the commented-out dataArray the data that I want was successfully retrieved.

However, error is prompted when I use the dataArray returned from this.http.get().

How can I properly access the data array?

// var dataArray = [{ id: 15, name: "111" }, { id: 13, name: "abc" }];
var dataArray = this.http.get(apiURL).subscribe(response => response.text());

const userID = this.route.snapshot.paramMap('id');
var user = dataArray.find(x => x.id === userID);
this.userForm.patchValue(user);
Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
Wei Hang Tan
  • 15
  • 1
  • 7

1 Answers1

1

.subscribe returns a Subscription and not the actual data you want to use. In order to use the data that is returned, you have to work within the callback to .subscribe. Please see How do I return the response from an asynchronous call? for a more in-depth explanation of code synchronization in JavaScript.

TypeScript errors are usually helpful. In this case it's telling you that type Subscription doesn't have a method .find. This is true ... and the reason is that dataArray is a Subscription (returned from the call to .subscribe) and not an array as you expect.

If you want to use the array returned from the response, you will have to access it inside of .subscribe:

this.http.get(this.apiURL).pipe(
  map(response => response.text()),
).subscribe(dataArray => {
  this.userForm.patchValue(dataArray.find(
    user => user.id === this.route.snapshot.paramMap.get('id'),
  ));
});

Also, I don't think you should need to get every user for patchValue. Ideally you could do something like this.http.get(`/users/${userId}`) and skip the .find.

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405