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
Using Subscribe and takeUntil
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();
}
}
Using a Pipeable Operator with an Empty Subscribe
export class ExampleComponent implements OnInit {
users: User[];
constructor(
private userService: UserService
) { }
ngOnInit() {
this.userService.getUsers()
.pipe(map(users => this.users = users))
.subscribe();
}
}