简体   繁体   中英

Can't assign value to variable in ngOnInit()

I do the call to api in ngOnInit() and I want to do some more things on data from api in ngOnInit() .

But when I try to console.log() my data I got undefined and can not process more. When I console.log() the same data in getUsers() method when I subscribe data from service I have my array with json data. Api response:

{"items":[{"id":"1","name":"Adam","age":20},{"id":"2","name":"Cris","age":32}]}

UserResults is my whole JSON. And I need only users in my users Array not item.

service.ts

public getUsers(): Observable<UserResults> {
    return this.httpClient.get<UserResults>(baseURL);
  }

component.ts

export class SidebarComponent implements OnInit {
  usersResult: UserResults;
  users: Users[];


  constructor(private dataService: DataService) { }

  ngOnInit(): void {
    this.getUsers();
    // shouldn't be users array available ???
    console.log(this.getUsers()) // undefined
    ///more calculations
  }

  private getUsers() {
    this.dataService.getUsers().subscribe(
      data => {
        this.users = data.items;
    console.log(this.getUsers()) // correct data in json array
      }
    )
  }
}

How should I handle it the best way?

You are trying to console.log your method, which returns nothing and is asynchronous, rather than the data returned.

If you really need the data within the ngOnInit , you need to subscribe to your Observable in there, and not in a separate private method.

Note that this is not generally the best way to handle data returning from an HTTP request. Depending on how the data is consumed, you would generally want to create the Observable in your TypeScript code, and subscribe to it in the template with the async pipe wherever possible. For example:

component.ts:

this.users$ = this.dataService.getUsers().pipe(
  map(data => data.items) // this is now an Observable<User[]>
);

component.html:

<div class="user-pane" *ngFor="let user of (users$ | async)">

Don't forget that asynchronous stuff takes time. You can't call an asynchronous method in one line and then consume the results in the following line.

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