【问题标题】:Angular 8 Pipe - Variable is undefined outside SubscriptionAngular 8 Pipe - 在订阅之外未定义变量
【发布时间】:2020-05-18 10:18:45
【问题描述】:

如何访问角管道中订阅内的变量以返回转换后的值?

我尝试了什么

transform(value: any, ...args: any[]): any {

  const clientKey = args[0];
  let arr = [];
  let newValue;


  this.dbJobs.getJobsFromKey(clientKey).pipe(take(1)).subscribe(jobs => {
    if (jobs && jobs.length) {

      jobs.forEach((job) => {
        arr.push(job.time);
      });
    }
    newValue = arr.reduce((a, b) => {
      return a + b;
    }, 0);

    return newValue;
  });

  return newValue;
}

newValue 变量在此示例中未定义。我如何检索它们以返回此订阅之外的管道的新值?

【问题讨论】:

  • 不,这不是解决方案,因为在订阅中返回变量对管道没有影响。我需要订阅之外的这个值来返回它..
  • 订阅里面return newValue;有什么作用?
  • 这是一个角管 (angular.io/guide/pipes)。我需要在transform 函数中使用oldValue | newValuePipe 更改一个值,我需要返回新值。如果我在订阅中返回它,什么都不会发生。
  • 请参考malcoded.com/posts/angular-async-pipe,异步管道上的好帖子。

标签: angular typescript subscription


【解决方案1】:

您希望以同步方式获取异步数据。这样不行。

在您的管道中,您应该返回 Observable 值。在这种情况下,您在 map Rxjs 运算符中修改您的数据,而不是在订阅中。

transform(value: any, ...args: any[]): any {

  const clientKey = args[0];
  let arr = [];
  let newValue;


  return this.dbJobs.getJobsFromKey(clientKey)
    .pipe(
      take(1),
      map(jobs => {
    if (jobs && jobs.length) {

      jobs.forEach((job) => {
        arr.push(job.time);
      });
    }
    newValue = arr.reduce((a, b) => {
      return a + b;
    }, 0);

    return newValue;
  }));
}

当你想在模板中使用这个管道时,你必须将它与AsyncPipe连接起来

例如:data | yourPipe | async

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-14
    • 2020-06-28
    • 2022-07-29
    • 2017-06-19
    • 2020-08-12
    • 2017-04-01
    • 1970-01-01
    相关资源
    最近更新 更多