简体   繁体   中英

Angular Http subscribe - cannot assign to variable in component

I want to retrieve data from api and assign it to some value inside the angular component. In subscribe I'm trying to assign the data to loggedUser and then call function inside this subscribe to navigate to another component with this received object. Unfortunately I got the error : The requested path contains undefined segment at index 1 . I want to have this object set outside the subscribe too. How can I achieve this?

 logIn() {
      this.portfolioAppService.logIn(this.loggingUser).subscribe((data) => {
      this.loggedUser = data;
      console.log(this.loggedUser);
      console.log(data);
      this.navigateToProfile(this.loggedUser.Id);
    });
  }

  navigateToProfile(id: number) {
    this.router.navigate(['/profile', id]);   
  }

console output

You are using an incorrectly named property when calling navigateToProfile .

From your console output, I can see that the data object in the subscribe looks like this:

{
  id: 35,
  // ..
}

But you are calling the function like this:

this.navigateToProfile(this.loggedUser.Id);

Instead, use the property id (lower case)

this.navigateToProfile(this.loggedUser.id);

To narrow this problem down in the future, try being more specific in your testing. Humans are good at seeing what they want to see and will assume the problem is more complicated than it is. If you had tried console.log(this.loggedUser.Id) , you would have seen the result undefined , and worked out the problem yourself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM