user.src
user.src

Reputation: 29

Convert ActivatedRoute.queryParams to Promise

I don't want to subscribe to route.queryParams as an Observable but want to make it a Promise to be able to use async/await to do various function calls in ngOnInit. Unfortunately I fail at this intention. The following implementation gives me no reaction or output:

constructor(private route: ActivatedRoute) { }

  async ngOnInit() {
    this.route.queryParams.toPromise().then(res => {
      console.log(res);
    });
  }

What am I doing wrong? Thx!

Upvotes: 1

Views: 832

Answers (1)

AliF50
AliF50

Reputation: 18849

I think since queryParams is an observable that is long lived, you can't convert it to a promise like so. You need a take operator on it to take the first emission and convert that to a promise.

import { take } from 'rxjs/operators';
....
constructor(private route: ActivatedRoute) { }

  async ngOnInit() {
    // add pipe(take(1)) here to take the first emission, close the stream,
    // and convert it to a promise.
    this.route.queryParams.pipe(take(1)).toPromise().then(res => {
      console.log(res);
    });
  }

Upvotes: 3

Related Questions