如何在可观察的查找中将项目移动到集合顶部

时间:2018-11-19 21:23:44

标签: angular typescript rxjs observable

Rxjs的新功能。我熟悉管道,过滤器,排序,地图等,但无法解决此问题。我需要在可观察的返回数据中找到一个项目,并将其移到顶部,然后再显示。在此示例中,达斯·维达(Darth Vader)是项目4,我想在可观察到的数组/集合中查找并移动到第0个或第一个位置。 https://stackblitz.com/edit/findandmakefirst

2 个答案:

答案 0 :(得分:1)

import { People } from './sw-people.model';

interface Results {
  count: Number,
  next: String,
  previous: string,
  results: People[],
}

@Injectable()
export class SwPeopleService {
    people$ = this.http.get('https://swapi.co/api/people/')
      .map((res: Results) => {
         return res.results.sort((a: People, b: People) => {
           return a.name === "Darth Vader" ? -1 : b.name === "Darth Vader" ? 1 : 0;
         });
        });

    constructor(private http: HttpClient) {} 
}

答案 1 :(得分:0)

喜欢吗?

people$ = this.http.get('https://swapi.co/api/people/')
  .map((res:any) => {
    var _vader = res.results.splice(res.results.findIndex(x => x.name === 'Darth Vader'), 1);
    return [..._vader, ...res.results];
  });