Reputation: 66
Say I have a component and I call my api service to return me an observable of type User[]
, emitting only one value. What way is preferred to setting my global variable?
Note: I am not using an async pipe within my html file in this example
export class ExampleComponent implements OnInit, OnDestroy {
users: User[];
ngUnsubscribe: Subject<unknown> = new Subject<unknown>();
constructor(
private userService: UserService
) { }
ngOnInit() {
this.userService.getUsers()
.pipe(takeUntil(this.ngUnsubscribe))
.subscribe(res => this.users = res);
}
ngOnDestroy() {
this.ngUnsubscribe.next();
this.ngUnsubscribe.complete();
}
}
export class ExampleComponent implements OnInit {
users: User[];
constructor(
private userService: UserService
) { }
ngOnInit() {
this.userService.getUsers()
.pipe(map(users => this.users = users))
.subscribe();
}
}
Upvotes: 0
Views: 619
Reputation: 415
this.userService
.getUser()
.pipe(take(1))
.subscribe((user) => {
this.userList = user;
});
Or you can use in async pipe in HTML like this
user$|async
Upvotes: 0