Angular中如何对NYT API返回的影评数据按日期倒序排序
实现按日期降序排序的两种方案
方案1:接口侧直接返回排序后数据(推荐)
NYT影评接口原生支持排序参数,直接在请求时追加参数即可,无需前端额外处理,性能更优。
修改reviews.service.ts代码:
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> { // 追加排序参数,按发布日期降序返回 const requestParams = new HttpParams() .set('sort', 'publication_date') .set('order', 'desc'); return this.http.get(this.apiUrl, { params: requestParams }).pipe(map((response:any)=>response.results)) } }
方案2:前端本地排序
如果不需要调整接口请求,直接在拿到返回结果后做本地排序即可:
修改reviews.component.ts代码:
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) => { // 按发布日期降序排序,publication_date为NYT接口返回的标准发布日期字段,可按需替换为你需要的日期字段 this.data = data.sort((itemA: any, itemB: any) => { return new Date(itemB.publication_date).getTime() - new Date(itemA.publication_date).getTime(); }); console.log(typeof this.data); console.log(this.data); }, error: (err: any) => { console.log(err); }, complete: () => { console.log('complete'); } }); } }
- 注意:如果NYT接口的排序参数和示例不同,直接调整参数即可,方案2无需调整接口参数,兼容性更强。
内容的提问来源于stack exchange,提问作者547n00n
相关产品推荐
相关产品推荐

