I am trying to learn routing by adding routing to a specific page in my healthcare app using angular. When I am trying to fetch data this is error what we are getting:
users.component.ts:15 ERROR TypeError: Cannot read properties of undefined (reading 'State')
at Object.next (users.component.ts:17:40)
at ConsumerObserver.next (Subscriber.js:91:33)
at SafeSubscriber._next (Subscriber.js:60:26)
at SafeSubscriber.next (Subscriber.js:31:18)
at map.js:7:24
at OperatorSubscriber._next (OperatorSubscriber.js:13:21)
at OperatorSubscriber.next (Subscriber.js:31:18)
at filter.js:6:128
at OperatorSubscriber._next (OperatorSubscriber.js:13:21)
at OperatorSubscriber.next (Subscriber.js:31:18)
I am writing this code for fetching the value of "data" from Data response getting from api
ngOnInit(): void {
//Fetch Users
this.userService.getAllUsers()
.subscribe(
(successResponse)=>{
console.log(successResponse[0].State);
},
(errorResponse)=>{
console.log(errorResponse);
}
)
}
This code is giving the output
users.component.ts:15 ERROR TypeError: Cannot read properties of undefined (reading 'State')
Please help me with this as why the data is not fetching properly?
Why is
successResponse[0].State
not giving the correct output?
CodePudding user response:
According to your ScreenShot, it does not contain a key called State. So if you want to access all the data retrieved, the code should be changed as follows:
ngOnInit(): void {
//Fetch Users
this.userService.getAllUsers()
.subscribe(
(successResponse)=>{
console.log(successResponse.data);
},
(errorResponse)=>{
console.log(errorResponse);
}
)
}
CodePudding user response:
make it like this:
ngOnInit(): void {
//Fetch Users
this.userService.getAllUsers()
.subscribe(
(successResponse)=>{
console.log(successResponse.data[0].State);
},
(errorResponse)=>{
console.log(errorResponse);
}
)
}