簡體   English   中英

可觀察的異步過濾器使用 RxJs 在 Angular 5 中按日期字段對 json 響應進行排序

[英]Observable Async filter to sort json response by date field in Angular 5 using RxJs

Observable 正在捕獲一個類似於 json 的 API 響應。

[
  {
    "name": "Vijay",
    "effectivedate": "2018-02-08T15:04:46.000Z",
    "expirationdate": "2018-02-22T15:04:46.000Z"
  },
  {
    "name": "Thulasi",
    "effectivedate": "2018-01-23T04:42:33.000Z",
    "expirationdate": "2018-01-30T04:42:33.000Z"
  },
  {
    "name": "Robert",
    "effectivedate": "2018-01-22T18:42:30.000Z",
    "expirationdate": "2018-01-28T18:42:30.000Z"
  },
  {
    "name": "Pakkiyaraj",
    "effectivedate": "2018-02-12T09:04:47.000Z",
    "expirationdate": "2018-02-28T08:48:58.000Z"
  },
  {
    "name": "Violet",
    "effectivedate": "2018-02-20T11:51:27.221Z",
    "expirationdate": "2018-02-22T11:49:37.000Z"
  }
]

TypeScript 文件具有 API 調用和管理對響應數據的可觀察性。

 this.gridResult$ = this.http.get(`**URL HERE**`)
    .map((result: any[]) => {
      return result;
    }, (err) => {
      console.log(err);
      this.error.error(err);
    });

我的 HTML 有這個片段。

<tr *ngFor="let result of gridResult$ | async">
    <td>{{result.name}}</td>
</tr>

我需要使用effectivedate的日期排序將 json 響應排序到表中。 請讓我知道是否可以在 RxJs 中使用任何過濾器。

隨着幫助lodashmoment ,你可以不喜歡這樣寫道:

var sortedData = _.sortBy(names, function(o) { return  
    moment(o.effectivedate); 
}).reverse();

//OR (With ES6 way)

var sortedData = _.sortBy(names,(o) => moment(o.effectivedate) ).reverse();

 var names = [ { "name": "Vijay", "effectivedate": "2018-02-08T15:04:46.000Z", "expirationdate": "2018-02-22T15:04:46.000Z" }, { "name": "Thulasi", "effectivedate": "2018-01-23T04:42:33.000Z", "expirationdate": "2018-01-30T04:42:33.000Z" }, { "name": "Robert", "effectivedate": "2018-01-22T18:42:30.000Z", "expirationdate": "2018-01-28T18:42:30.000Z" }, { "name": "Pakkiyaraj", "effectivedate": "2018-02-12T09:04:47.000Z", "expirationdate": "2018-02-28T08:48:58.000Z" }, { "name": "Violet", "effectivedate": "2018-02-20T11:51:27.221Z", "expirationdate": "2018-02-22T11:49:37.000Z" } ]; var sortedData = _.sortBy(names, function(o) { return moment(o.effectivedate); }) .reverse(); console.log(sortedData); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.core.js"></script> 

您可以直接在 rxjs 映射中使用標准 Javascript 排序,如下所示:

this.gridResult$ = this.http.get(`**URL HERE**`).pipe(
  map(result => result.sort((a, b) => a.value - b.value)) // you do your sorting here
);

它會返回 observable

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM