Search code examples
javascriptangulartypescripthttpsubscribe

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


Solution

  • 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.