angular - Angular 8 Pipe - 在订阅之外未定义变量
问题描述
如何访问角管道中订阅内的变量以返回转换后的值?
我试过的
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
变量未定义。我如何检索它们以返回此订阅之外管道的新值?
解决方案
您希望以同步方式获取异步数据。这行不通。
在您的管道中,您应该返回 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
推荐阅读
- angular - “OperatorFunction”类型上不存在属性“订阅”
' - node.js - 通过 Crontab 自动导出 amCharts-PDF-Export?
- reactjs - 检查 If/Else 块奇怪行为中的空数组
- python-3.x - 导入子模块然后从脚本调用函数
- php - Slim (V3) 框架:为生成的链接添加前缀,但不为传入路由添加前缀
- visual-studio - Unity3D 与 Visual Studio 2019 - 自动刷新
- python - 来自 multipart/form-data 原始套接字的 Python 解码文件
- stored-procedures - 环回节点 mssql:如何设置远程方法以使用存储过程的输出参数?
- google-apps-script - Google Ads 脚本:如何获取 30 天的数据,然后每天循环
- javascript - 在小屏幕尺寸上将引导导航栏置于顶部