Josh96
Josh96

Reputation: 66

Setting Component Property Within Pipe or Subscribe

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();
  }
}

Upvotes: 0

Views: 619

Answers (1)

Saransh Dhyani
Saransh Dhyani

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

Related Questions