试图对返回的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;
}
EventsService.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<Event[]> {
return this.http.get<Event[]>(this.eventsUrl); // DO I ADD A PIPE OR MAP HERE AND HOW DO I DO IT?
}
}
EventsList.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?
}
}
答案 0 :(得分:3)
您将需要在服务中对它进行排序并在组件中进行订阅,因此您的服务会有一些麻烦,
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);
}
答案 1 :(得分: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;
});
答案 2 :(得分:1)
我将添加一个map
以便直接在您服务的getEvents
函数中对事件进行排序。这样,每个使用该服务的类都可以观察到您已经排序的事件:
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()
))
);
}
答案 3 :(得分:0)
这是我的解决方案。我会使用点击运算符。
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))
}