3

尝试对返回的 Observable.subscribe() 数据数组进行排序... Angular 7 的新手。我对如何在这里使用 RXJS 方法、我需要在哪里导入什么以及如何对 Event 类型的数组进行排序感到困惑。

事件.ts

import {Venue} from './Venue';

export class Event {
  id: number;
  url: string;
  date: string;
  venue_id: number;
  venue: Venue;
}

事件结果对象.ts

import {Event} from './Event';

export interface EventResultObj {
  count: number;
  next?: any;
  previous?: any;
  results: Event[];
}

事件服务.ts:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Event } from '../models/Event';
import {Observable} from 'rxjs';
@Injectable({
  providedIn: 'root'
})
export class EventsService {
  eventsUrl = 'http://localhost:4200/assets/tempData/events.json';
  constructor(  private http: HttpClient) { }

  getEvents(): Observable<EventResultObj> {    
    return this.http.get<EventResultObj>(this.eventsUrl).pipe(
          /// CANNOT FIGURE OUT HOW TO GET A SORT FUNCTION TO WORK HERE 
          /// WITH THE OBSERVABLE
    )
  }
}

事件列表.ts

import {Component, OnInit} from '@angular/core';
import {EventsService} from '../../services/events.service';

@Component({
  selector: 'app-buyer-events-list',
  templateUrl: './buyer-events-list.component.html',
  styleUrls: ['./buyer-events-list.component.scss']
})
export class BuyerEventsListComponent implements OnInit {

  constructor(private eventsService: EventsService) {
  }

  events;

  ngOnInit() {
    this.eventsService.getEvents().subscribe(events => this.events = events); // OR DO I ADD A PIPE OR MAP HERE AND HOW DO I DO IT?
  }

}
4

4 回答 4

5

您需要在您的服务中对其进行排序并在组件中订阅,因此您的服务将具有类似的东西,

 getEvents(): Observable<Event[]> {    
    return this.http.get<Event[]>(this.eventsUrl).pipe(
        map(events => events.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime()))
    ) ;
  }

接着,

 ngOnInit() {
    this.eventsService.getEvents().subscribe(events => this.events = events); 
  }
于 2019-02-16T17:12:31.227 回答
4

我会添加一个map直接在getEvents您服务的函数中对事件进行排序。这样,使用该服务的每个类都将获得已排序的事件的 observable:

import { map } from 'rxjs/operators';

getEvents(): Observable<Event[]> {    
  return this.http.get<Event[]>(this.eventsUrl).pipe(
    map(events => events.sort((a: Event, b: Event) =>
      (new Date(a.date)).getTime() - (new Date(b.date)).getTime()
    ))
  );
}

于 2019-02-16T17:14:03.237 回答
2

在服务中,您使用管道和地图!

public getEvents(): Observable<any> {
    return this.http.get(this.eventsUrl).pipe(map(response => response));

}

在您的组件中使用订阅!

this.eventsService.getEvents()
 .subscribe(events => {
   console.log(events); // Example
 }, err => {
   throw err;
 });
于 2019-02-16T17:20:52.030 回答
1

这是我的解决方案。我会使用水龙头运算符。

const  sortById = function(data) {
  data.sort((a,b) => data.id - data.id);
};


getEvents(): Observable<Event[]> {    
  return this.http.get<Event[]>(this.eventsUrl)
    .pipe(tap(sortById))
}   

于 2019-06-26T14:56:53.390 回答