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.
I used this example to no luck:
How to check if a RxJS Observable contains a string in Angular2?
I have this service:
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,
) { }
}
In your component:
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);
}
Should be changed to:
private verifyPaidOrder(): Observable<OrderModel[]> {
orderExists = false;
this.orderService.getOrders()
.subscribe(
(response) => {
this.allOrders = response;
//orderExists will be true if there are any with whateverOrderId you want to check for
orderExists = response.some(x => x.orderId === whateverOrderId) ? true : false;
});
}
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.