从提取的数据中过滤特定数据

时间:2019-06-16 10:53:27

标签: angular typescript

我想从数据库中过滤特定数据并将其返回到页面。 我的策略是在服务中使用httpClient get方法,仅获取 具体数据。我该如何处理过滤

到目前为止,我可以获取testurl中包含的所有数据,但是我不知道如何过滤特定的数据

data.json

[
    {"allOrders":21},
    {"pendingConfirmOrders":14},
    {"pendingPaymentOrders":8}
]

order-history.component.ts

import { orderHistoryService } from './../../infrastructure/services/order-history.service';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-order-history-page',
  templateUrl: './order-history-page.component.html',
  styleUrls: ['./order-history-page.component.scss']
})
export class OrderHistoryPageComponent implements OnInit {
orderHistory:any;
confirmOrder;
  constructor(private orderService:orderHistoryService) {
    this.orderService.getOrderHistory().subscribe((response:any)=>{
      this.orderHistory = response;
    });
   }
  _orderHistory(){
    console.log(this.orderHistory);
  }
  _pendingConformation(){
    this.confirmOrder=this.orderHistory.filter(orders=> this.orderHistory
      .includes(this.confirmOrder));
  }

  ngOnInit() {
  }

}



orderService.ts

import { Injectable } from '@angular/core';
import { AppSettings } from '../../app.setting';
import { ApiService } from './api.service';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';


@Injectable({
  providedIn: 'root'
})
export class orderHistoryService {
    private testUrl='../../../assets/data/orders.json';
//   _baseUrl = AppSettings.BACKEND2_SUBSCRIBE_BASE;
  constructor(private _apiService: ApiService, private _http: HttpClient) { }
  getOrderHistory():Observable<any>{
    return this._http.get<any>(this.testUrl);
    //  const endpoint = `${AppSettings.SERVER_API}`//endpoint;
    //  return this._http.get(endpoint);
  }
  /**
 * THIS METHOD GET The history of orders
 */
}

我编写的函数返回一个空数组

1 个答案:

答案 0 :(得分:0)

由于data.json是JSON对象的数组,因此,当您创建JavaScript变量来保存API响应中的数据时,需要包括数组的索引。

创建变量应如下所示:

allOrders = orderHistory[0].allOrders;
pendingConfirmOrders = orderHistory[1].pendingConfirmOrders;
pendingPaymentOrders = orderHistory[2].pendingPaymentOrders;

这仅在您知道data.json的结构不会改变的情况下才有效。如果您可以控制API,则建议您删除数组,并使输出看起来像这样:

{
"allOrders":21,
"pendingConfirmOrders":14,
"pendingPaymentOrders":8
}

这样,您就可以省略数组索引并按照上面的注释中的说明访问数据-使用orderHistory.pendingConfirmOrders;