Home > Software design >  "Cannot read properties of undefined (reading 'id')" error when loading page in
"Cannot read properties of undefined (reading 'id')" error when loading page in

Time:02-28

I am pulling data from a mockapi service in angular. I pulled all the data without any problems, then I tried to access the details of the data with the id of any data in the list. I think the function I want all the data runs later and I get this error.

app.component.ts file

export class AppComponent implements OnInit {
  
  data:Array<any>
  userData!: User;
  
  constructor(private task: TaskService) {
    this.data = new Array<any>();
  }
  
  ngOnInit(): void {
      this.runTask();
  }

  runTask() {
    this.task.getData().subscribe((data) =>{
      this.data = data;
    });
  }

  getUserData = (id: number) => {
    if (this.runTask == null) {
      return
    }
    this.task.getUserData(id).subscribe((res: User) => {
      console.log(res);
      this.userData = res;
    })
  }
}

export interface User{
  id: number,
  name: string,
  phone: number,
  website: string,
  company: any
}

task.service file

export class TaskService {

  readonly URL;

  constructor(private http: HttpClient) { 
    this.URL = "https://jsonplaceholder.typicode.com/users/"
  }

  getData(): Observable<any> {
    return this.http.get(this.URL);
  }

  getUserData(id: any) {
    return this.http.get<User>(this.URL id.id);
  }
}

screenshot

first load

When I click on the view button, the data in the id I want comes. A modal is opened and when I close the modal, all the data is received.

I've been researching the problem for hours and couldn't find a solution.

CodePudding user response:

The id is a number in your component but it's use in the service as an object. update your service as below

  getUserData(id: number) {
    return this.http.get<User>(this.URL   id);
  }

CodePudding user response:

The error you are getting (that I see in the screenshot) comes from your template file 'app.component.html' in line 90. It seems you are trying to read the id from an undefined variable (a variable that has not been loaded (yet)).

Make sure that it is defined, you can for example test if the variable is truthy using 'NgIf' like below:

<div *ngIf="user">
  <span>{{user.id}}</span>&nbsp;
  <span>{{user.name}}</span>
</div>

To avoid errors of types passed to methods (like the one found by Roy Christo), try not to use the 'any' keyword.

  • Related