[英]How can I filter an ID by subscribing to an Observable
Below I am subscribing to an observable but just updating values for the first object.下面我订阅了一个可观察的但只是更新第一个 object 的值。 I am passing through ID = 413 I would like to filter the ID so I can only get that object, can anyone help me please?
我正在通过 ID = 413 我想过滤 ID 所以我只能得到 object,有人可以帮我吗?
Thanks谢谢
this.Ordersummary.subscribe(
r => {
if (r.length != 0) {
this.thepackage = r[0];
this.emptySummary = true;
} else {
this.router.navigate(['packages/gbr/public']);
}
});
You can always use map and filter.您始终可以使用 map 和过滤器。 Or if you want the subscribe to only trigger for a specific value, then you have to filter first.
或者,如果您希望订阅仅触发特定值,则必须先进行过滤。
Something like this:像这样的东西:
pipe(
filter(item => item.ID === 413)
).subscribe(val => console.log(val));
If you want to filter only the necassary id then you may create a simple method like this,如果您只想过滤 necassary id,那么您可以创建一个像这样的简单方法,
filterById(yourId: number) {
this.filteredPackage = this.thepackage.filter(package => package.id === yourId);
}
Explanation:解释:
After assigning your response to the this.thepackage
object inside subscribe(), your response is globally accessible via this.thepackage
object.将您的响应分配给 subscribe() 内的
this.thepackage
object 后,您的响应可通过this.thepackage
object 全局访问。 In order to get the single record who's ID is 413, just pass the ID into the method filterById()
.为了获取 ID 为 413 的单条记录,只需将 ID 传递给方法
filterById()
。 Since it's bad to modify the original object, we assign the newly filtered item to a new variable this.filteredPackage
.由于修改原始 object 是不好的,我们将新过滤的项目分配给一个新变量
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));
I am not getting anything in console when I click on item 413当我单击项目 413 时,我在控制台中没有得到任何东西
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.