lisa
lisa

Reputation: 107

Angular: Still not getting the value after subscribe

In my ts file I have this function:

searchForUser() {
        this.userService.getUserByLastName(this.searchString)
            .subscribe(
                (data: User) => this.searchedUser = data
            );
        console.log('Firstname: ' + this.searchedUser.firstName);
        this.dataService.changeUser(this.searchedUser);
    }

In my html file I get the correct values from searchedUser. In my console.log and dataService not. Why? When I do a second search I am getting the values from the search before.

Upvotes: 2

Views: 1366

Answers (2)

dev-dan
dev-dan

Reputation: 6283

This is a timing issue, move all the actions requiring the response into the subscription call back in order to access the value you need.

public searchForUser(): void
{
    this.userService.getUserByLastName(this.searchString).subscribe((data: User) => 
    {
        this.searchedUser = data;
        console.log('Firstname: ' + this.searchedUser.firstName);
        this.dataService.changeUser(this.searchedUser);
    });         
}

This errors are occurring because you are trying to access this.searchedUser before it has been defined in the subscription.

Upvotes: 2

porgo
porgo

Reputation: 1737

move

console.log('Firstname: ' + this.searchedUser.firstName);
this.dataService.changeUser(this.searchedUser);

inside subscribe:

searchForUser() {
  this.userService.getUserByLastName(this.searchString)
    .subscribe((data: User) => {
      this.searchedUser = data;
      console.log('Firstname: ' + this.searchedUser.firstName);
      this.dataService.changeUser(this.searchedUser);
     });
 }

You can also check my response here: https://stackoverflow.com/a/55726693/6713046 for explanation.

Upvotes: 2

Related Questions