【问题标题】:angular : How to sort fetched data from api by date角度:如何按日期对从 api 获取的数据进行排序
【发布时间】:2022-01-12 02:14:48
【问题描述】:

我从 NYT api 获取电影评论,我想按日期按降序对结果进行排序,如何添加此过滤器?

服务

import { HttpClient, HttpParams } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';
import { GlobalConstants } from '../common/global-constants';
import {map} from 'rxjs/operators';
@Injectable()
export class ReviewsService {
  apiUrl = GlobalConstants.apiURL;

  constructor(private http: HttpClient) {
  }

  getReviews(): Observable<any> {
    return this.http.get(this.apiUrl).pipe(map((response:any)=>response.results))
  }
}

组件

import { Component, OnInit } from '@angular/core';
import { ReviewsService } from 'src/app/services/reviews.service';
@Component({
  selector: 'app-reviews',
  templateUrl: './reviews.component.html',
  styleUrls: ['./reviews.component.css']
})
export class ReviewsComponent implements OnInit {

  data: any;
  constructor(private reviewsService: ReviewsService) { }

  ngOnInit() {
    this.getReviews();
  }

  getReviews() {
    this.reviewsService.getReviews().subscribe({
      next: (data: any) => {
        this.data = data;  
        console.log(typeof this.data);
        console.log(this.data);
        
              
      },
      error: (err: any) => {
        console.log(err);
      },
      complete: () => {
        console.log('complete');
      }
    });
  }

}

【问题讨论】:

    标签: angular api date sorting filter


    【解决方案1】:

    为您服务:

         getReviews(): Observable<any> {
           return this.http.get(this.apiUrl).pipe(map((response: any) 
           => response.results.sort((dataA, dataB) => {
           return ((+new Date(dataA['publication_date'])) - (+new 
           Date(dataB['publication_date'])));
         })))
        }
    

    【讨论】:

    • 有道理,谢谢 Bellarej
    猜你喜欢
    • 1970-01-01
    • 2011-09-08
    • 2019-01-17
    • 2020-06-04
    • 1970-01-01
    • 2016-10-15
    • 1970-01-01
    • 1970-01-01
    • 2016-11-07
    相关资源
    最近更新 更多