Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Observable displays data before being populated, Angular

I’m making a simple API call to get users data, here’s the service:
the service contains setUsers() method that allows to populate userSubject

@Injectable({
  providedIn: 'root'
})
export class UserService {

  API_URL = 'https://jsonplaceholder.typicode.com/users';
  private userSubject = new BehaviorSubject<User[]>([]);
  public users = this.userSubject.asObservable();

  constructor(private httpClient: HttpClient) {
    console.log("Users" ,this.users);
  }

  public setUsers() {
    this.httpClient.get<User[]>(this.API_URL)
      .pipe(
        catchError(() => {
          this.userSubject.error('An error occurred');
          return [];
        }),
        map((users) => {
          return users;
        })
      )
      .subscribe((users) => {
        this.userSubject.next(users);
      })
  }
}

then i called usersService from userComponent

export class UsersComponent implements OnInit {
  users$ = this.userService.users;



  constructor(private userService: UserService) { }

  ngOnInit(): void {
    console.log("calling setUsers() from users component...", this.users$);
    this.userService.setUsers();
  }

}

and when a run the project in the browser it displays the observable (the console.log in the constructor) with the data even before calling setUsers() method that initialize the data !? can someone please explains me why the observable contains the data before initializing
(https://i.stack.imgur.com/IBTN8.png)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This is an artifact of the lazy evaluation in the chrome devTools console.

You see that small blue "i", when you hover over it you will see the tooltip

This value was evaluated upon first expanding. It may have changed since then.

This means the console shows you the value the object has at the moment you expand it (which you did after the request was sent).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading