Matt Knight Matt Knight - 3 years ago 310
TypeScript Question

Angular 4 - How to check if observable contains a string

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
.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 {

public orderId: number,
public firstName: string,
public lastName: string,
public emailAddress: string,
public organizationName: string,
public city: string,
public state: string,
public zipCode: number,
) { }


Answer Source

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;

    (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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download