![](/img/trans.png)
[英]Angular2 rxjs sort (observable) list of objects by an observable field
[英]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 中使用任何過濾器。
隨着幫助lodash
和moment
,你可以不喜歡這樣寫道:
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.