Angular 4 - 如何检查observable是否包含字符串

时间:2017-09-29 19:53:26

标签: angular typescript

我正在尝试确定observable是否包含字符串。问题是双重的。如何将结果映射回一个对象,然后一旦我有了该对象,确定它是否包含特定的orderId。

我用这个例子没有运气: 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,
        ) { }

    }

3 个答案:

答案 0 :(得分:2)

在您的组件中:

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()。你订阅了它。如果要在服务返回到您调用服务的位置之前检查服务中是否存在订单,那么在将带有您的数据的observable返回之前,将检查置于map()内。

答案 1 :(得分:1)

错误消息告诉您正在访问该阵列,并且该阵列没有名为orderId的属性。您需要在数组中找到订单。

我做了类似的事情,我的代码看起来像这样:

    return this.getProducts()
        .map((products: IProduct[]) => products.find(p => p.productId === id));

它使用产品阵列上的find。

你应该可以做类似的事情:

this.orderService.getOrders().map(x => x.find(o => o.orderId == id));  

答案 2 :(得分:-1)

您的班级应该有一个名为 orderId ;

的媒体资源
export class OrderModel {
        orderId : number;
        ......

        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,
        ) { }

    }