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.sstatic.net/IBTN8.png)
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).