Reputation: 499
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[]);
}
My component has this:
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);
...
}
My model is:
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,
) { }
}
Upvotes: 1
Views: 13634
Reputation: 1275
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() {
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);
});
}
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.
Upvotes: 2
Reputation: 60548
The error message is telling you that you are accessing the array and that the array does not have a property named orderId
. You need to find the order in the array.
I did something similar and my code looks like this:
return this.getProducts()
.map((products: IProduct[]) => products.find(p => p.productId === id));
It uses the find on the array of products.
You should be able to do something similar:
this.orderService.getOrders().map(x => x.find(o => o.orderId == id));
Upvotes: 2