简体   繁体   中英

Angular Showing: ERROR TypeError: Cannot read properties of undefined (reading 'State')

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?

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);
    }

    )

  }

make it like this:

ngOnInit(): void {
//Fetch Users
this.userService.getAllUsers()
.subscribe(
  (successResponse)=>{
    console.log(successResponse.data[0].State);
  },
(errorResponse)=>{
  console.log(errorResponse);
}

)

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM