0

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();
  }
}
Josh96
  • 56
  • 1
  • 8
  • What do you mean by global variable? – Berk Kurkcuoglu Aug 20 '20 at 17:51
  • @BerkKurkcuoglu My users property (variable) in my ExampleComponent – Josh96 Aug 20 '20 at 17:53
  • Both will work, but assigning inside subscription is the semantically correct way. Operators like `map` are used to transform the notifications from the source observable. – ruth Aug 20 '20 at 17:53
  • @MichaelD is there another pipeable rxjs operator that would work better? The benefit of using the pipe and empty subscribe method is that I don't have to every worry about unsubscribing from my observable (as well as less code). – Josh96 Aug 20 '20 at 17:55
  • You can chain pipes here, the first approach is better as you are unsubscribing on destroy to avoid memory leakes, also you can chain pipe operators, best way would be to you takeUntil + tap operator (instead of map) as you are not transforming the result. – Berk Kurkcuoglu Aug 20 '20 at 17:56
  • 1
    You can also avoid the unsubscribe subject part by using take(1) instead of takeUntil if your fetch operation is a one timer. – Berk Kurkcuoglu Aug 20 '20 at 17:58
  • 2
    @Josh96: It doesn't matter if the subscription is empty. Calling `subscription` on an observable will anyway open a data stream and you need to handle it's unsubscription. For easier ways to handle unsubscription you could refer here: https://stackoverflow.com/a/60223749/6513921 – ruth Aug 20 '20 at 18:00

1 Answers1

0
this.userService
            .getUser()
            .pipe(take(1))
            .subscribe((user) => {
                this.userList = user;
            });

Or you can use in async pipe in HTML like this

user$|async
Saransh Dhyani
  • 397
  • 3
  • 9