'"Cannot read properties of undefined (reading 'id')" error when loading page in Angular
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
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.
Solution 1:[1]
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);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Roy Christo |
