【问题标题】:Convert ActivatedRoute.queryParams to Promise将 ActivatedRoute.queryParams 转换为 Promise
【发布时间】:2021-05-03 22:24:09
【问题描述】:

我不想将 route.queryParams 订阅为 Observable,但希望将其作为 Promise,以便能够使用 async/await 在 ngOnInit 中执行各种函数调用。 不幸的是,我在这个意图上失败了。以下实现没有给我任何反应或输出:

constructor(private route: ActivatedRoute) { }

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

我做错了什么?谢谢!

【问题讨论】:

  • 他们对阻止您使用该功能的机制做了一些事情,但我不知道为什么或什么。您可能只需要坚持订阅功能。

标签: angular promise observable


【解决方案1】:

我认为由于queryParams 是一个长期存在的可观察对象,因此您不能将其转换为这样的承诺。您需要一个 take 运算符来获取第一个发射并将其转换为承诺。

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

【讨论】:

    猜你喜欢
    • 2017-01-12
    • 2016-07-05
    • 1970-01-01
    • 2022-01-07
    • 1970-01-01
    • 2016-12-25
    • 2018-02-19
    • 2018-04-23
    相关资源
    最近更新 更多