首页 > 解决方案 > 如何在可观察的情况下查找并将项目移动到集合顶部

问题描述

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

标签: angulartypescriptrxjsobservable

解决方案


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) {} 
}

推荐阅读