-1

This is my code:

  ngOnInit() {
    this.route.paramMap.subscribe(params => {
      console.log(params.get('id')); // THIS IS WORKS
      this.currentOrganization = this.getOrganizationId(params.get('id'));
      console.log(this.currentOrganization); // THIS IS UNDEFINED
    } );  
  }

  getOrganizationId(id: string) {
    let organizations = this.orgService.getOrganizations(); // THIS IS WORKS
    return organizations.find(p => p.id == id);
  }

Why undefined this.currentOrganization? How do I get the organization's information for params.get('id')?

Srijon Chakraborty
  • 2,007
  • 2
  • 7
  • 20
P. Mark
  • 81
  • 1
  • 3
  • 12
  • Does this answer your question? [How do I return the response from an Observable/http/async call in angular?](https://stackoverflow.com/questions/43055706/how-do-i-return-the-response-from-an-observable-http-async-call-in-angular) – R. Richards Feb 21 '21 at 13:54
  • Does the `return organizations.find(blah)` actually return the id or is it undefined? – Mike Tung Feb 21 '21 at 14:56
  • Maybe you can console.log `organizations.find(p => p.id == id)` first and see if it actually returns any value. – Belle Zaid Feb 21 '21 at 15:58
  • u have async problem. u need to subscribe it and take it inside subscribe – mr. pc_coder Feb 21 '21 at 16:30

1 Answers1

0

You can try add if(organizations) before the running the .find so it will only start to .find once there're values in organizations. Like so

getOrganizationId(id: string) {
    let organizations = this.orgService.getOrganizations();
    if(organizations) {
        console.log(organizations.find(p => p.id == id));
        return organizations.find(p => p.id == id);
    }
}

If you want to try a different approach, you may want to try this one

ngOnInit() {
    this.getOrganization();
}

getOrganization() {
    const organizationId = this.route.snapshot.paramMap.get('id');
    if (organizationId) {
      this.orgService.getOrganizations()
         .subscribe(org => {
                      console.log(org.find(p => p.id == organizationId));
                      return org.find(p => p.id == organizationId);
                    });
}

Though for me it's best to have a specific service that just returns the get with id as we do still take it from the route. It will be faster loading instead of having to go through it again once the data list has been fetch.

Belle Zaid
  • 172
  • 3
  • 9