Angular2 - OnInit : Values returned from Service' subscribe function does not get assigned to Component field/s

This is because this.getUsers() and then this.userService.getUsers().subscribe(...) only schedules a call to make a request to the server. Eventually when the response from the server arrives (console.log('ngOnit after getUsers() ' + this.users); was already executed before the call to the server was even made) then the function you passed to subscribe() is executed.

This should do what you want:

  getUsers() {
    return this.userService
    .getUsers()
    .map(
      (users) => {
        console.log('users ' + users);
        this.users = users;
        console.log('this.users ' + this.users);
      })
     .catch((error) => {
        console.log('error ' + error);
        throw error;
      });
    // users => this.users = users,
    // error => this.errorMsg = <any>error);
  }

  ngOnInit() {
    this.getUsers().subscribe(_ => {;
      console.log('ngOnit after getUsers() ' + this.users);
    });
  }

In getUsers() I use map() instead of subscribe, so we can subscribe later in order to be able to get code executed when the response arrived.

Then in ngOnInit() we use the subscribe() (subscribe() is necessary, otherwise would http.get() would never be executed) and pass the code we want to be executed when the response arrives.

I also changed function () to () =>. This way this works inside the following code block () => { ... }, otherwise it wouldn't.

Don't forget to add

import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';

otherwise these operators won't be recoginzed.

Tags:

Angular