Angular 4-如何检查observable是否包含字符串 [英] Angular 4 - How to check if observable contains a string
问题描述
我正在尝试确定可观察对象是否包含字符串.这个问题有两个方面.如何将结果映射回一个对象,然后当我拥有该对象时,确定它是否包含特定的orderId.
I am trying to determine if an observable contains a string. The issue is two-fold. How to map the results back to an object and then once I have that object, determining if it contains a specific orderId.
我用这个例子很不走运: 如何检查RxJS Observable是否包含Angular2中的字符串?
I used this example to no luck: How to check if a RxJS Observable contains a string in Angular2?
我有这项服务:
public getOrders(): Observable<OrderModel[]> {
return this.http
.get(this.apiURL)
.map(response => response.json() as OrderModel[]);
}
我的组件有这个:
private verifyPaidOrder(): Observable<OrderModel[]> {
//this works fine and gives me back everything.
// this.orderService.getOrders().subscribe(
// (response => this.allOrders = response),
// (err) => { this.handleError(err); });
// now, how do I determine if orderId exists?
// Property 'orderId' does not exist on type 'OrderModel[]
this.orderService.getOrders().map(x => x.orderId) <-- Can't do this!!
.first(roles => roles.indexOf(name) !== -1, undefined, false)
.map(val => !!val);
...
}
我的模特是:
export class OrderModel {
constructor(
public orderId: number,
public firstName: string,
public lastName: string,
public emailAddress: string,
public organizationName: string,
public city: string,
public state: string,
public zipCode: number,
) { }
}
推荐答案
在您的组件中:
private verifyPaidOrder(): Observable<OrderModel[]> {
this.orderService.getOrders().map(x => x.orderId) <-- Can't do this!!
.first(roles => roles.indexOf(name) !== -1, undefined, false)
.map(val => !!val);
}
应更改为:
private verifyPaidOrder() {
this.orderService.getOrders()
.subscribe(
(response) => {
this.allOrders = response;
//orderExists will be true if there are any with whateverOrderId you want to check for
this.orderExists = response.some(x => x.orderId === whateverOrderId);
});
}
当您实际上要呼叫服务时,就不再使用.map()
.您订阅它.如果要在订单返回到调用服务的位置之前检查订单中是否存在该服务,则可以将检查放在map()
中,然后再将observable随数据一起返回.
When you actually want to call your service, you don't use .map()
anymore. You subscribe to it. If you want to check if the order exists in the service BEFORE it gets returned to where you call the service, than you would put the check inside the map()
, before the observable is returned with your data.
这篇关于Angular 4-如何检查observable是否包含字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!