如何通过订阅 Observable 来过滤 ID
How can I filter an ID by subscribing to an 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']);
}
});
您可以随时使用地图和过滤器。或者,如果您希望订阅仅针对特定值触发,则必须先进行过滤。
像这样:
pipe(
filter(item => item.ID === 413)
).subscribe(val => console.log(val));
如果您只想过滤必要的 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
this.Ordersummary.pipe(
filter((item: any) => item.id === this.packageid)
).subscribe(val => console.log('VAL: ', val));
当我点击项目 413 时,我在控制台中没有得到任何东西
下面我订阅了一个可观察对象,但只是更新了第一个对象的值。我正在通过 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']);
}
});
您可以随时使用地图和过滤器。或者,如果您希望订阅仅针对特定值触发,则必须先进行过滤。
像这样:
pipe(
filter(item => item.ID === 413)
).subscribe(val => console.log(val));
如果您只想过滤必要的 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
this.Ordersummary.pipe(
filter((item: any) => item.id === this.packageid)
).subscribe(val => console.log('VAL: ', val));
当我点击项目 413 时,我在控制台中没有得到任何东西