0

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

2
  • What do you see from the console.log(data)? Can you add the output to the question Commented Mar 19, 2020 at 20:13
  • I added a link to console output - these two console.logs return same objects Commented Mar 19, 2020 at 20:20

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

7 Comments

But loggedUser is an User type object which has a field named "Id", when I change to "id" then it doesn't know what property is it. Maybe some problems in backend?
Are you sure that your mapping is right with your User type?Can you post the console.log(this.loggedUser)?
But this is Javascript. There is no Typescript in your browser. Typescript just allows you to model what you expect to happen at design time.
Your Typescript models should reflect the Javascript objects themselves. If you want your objects to have different names from the HTTP response, then map them in your service.
If not, then you need to change your Typescript model to match the HTTP response
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.