【问题标题】:How can I filter an ID by subscribing to an Observable如何通过订阅 Observable 来过滤 ID
【发布时间】:2019-11-21 20:45:14
【问题描述】:

下面我订阅了一个 observable 但只是更新第一个对象的值。我正在通过 ID = 413 我想过滤 ID,所以我只能获取该对象,有人可以帮我吗?

谢谢

this.Ordersummary.subscribe(
        r => {
            if (r.length != 0) {
                this.thepackage = r[0];
                this.emptySummary = true;
            } else {
                this.router.navigate(['packages/gbr/public']);
            }
        });

【问题讨论】:

  • 这里的ID是什么?
  • this.packageid = parseInt((this.route.snapshot.paramMap.get('id')));

标签: angular observable subscription


【解决方案1】:

您始终可以使用地图和过滤器。或者,如果您希望订阅仅触发特定值,则必须先进行过滤。

类似这样的:

pipe(
  filter(item => item.ID === 413)
).subscribe(val => console.log(val));

【讨论】:

  • 谢谢,但现在我得到属性 'id' 不存在于类型 'Ordersummary[]' this.Ordersummary.pipe( filter(item => item.id === this.packageid) ).subscribe( r => { if (r.length != 0) { console.log('R: ', r[0]); this.thepackage = r[0]; this.emptySummary = true; } else { this.router.navigate(['packages/gbr/public']); } });
【解决方案2】:

如果您只想过滤必要的 id,那么您可以创建一个像这样的简单方法,

filterById(yourId: number) {
    this.filteredPackage = this.thepackage.filter(package => package.id === yourId);
}

说明:

将您的响应分配给 subscribe() 中的 this.thepackage 对象后,您的响应可通过 this.thepackage 对象全局访问。要获取 ID 为 413 的单条记录,只需将 ID 传递给方法filterById()。由于修改原始对象不好,我们将新过滤的项目分配给一个新变量this.filteredPackage

this.filterById(yourId);    // yourId is 413 here

【讨论】:

  • 抱歉,我不太明白我会如何使用它
【解决方案3】:
this.Ordersummary.pipe(
        filter((item: any) => item.id === this.packageid)
    ).subscribe(val => console.log('VAL: ', val));

当我点击项目 413 时,我在控制台中没有得到任何东西

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-22
    • 2016-01-08
    • 1970-01-01
    • 1970-01-01
    • 2020-11-18
    • 2018-05-23
    • 2020-05-22
    • 2021-12-04
    相关资源
    最近更新 更多