Javascript Angular 6按键从observable对JSON进行排序
注意:我知道如何使用Javascript Angular 6按键从observable对JSON进行排序,javascript,angular,typescript,rxjs,observable,Javascript,Angular,Typescript,Rxjs,Observable,注意:我知道如何使用.sort()对常规对象数组进行排序,但这次我遇到了一个可观察对象,对此我并不熟悉 我正在使用服务获取对象的JSON数组: import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Injectable() export class MockDataService { private dataUrl = 'assets/data';
.sort()
对常规对象数组进行排序,但这次我遇到了一个可观察对象,对此我并不熟悉
我正在使用服务获取对象的JSON数组:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class MockDataService {
private dataUrl = 'assets/data';
constructor(private http: HttpClient) {}
get(filename: string) {
return this.http.get(`${this.dataUrl}/${filename}`);
}
}
使用此服务,我们只需传递一个json文件的文件名,即可获得一个可观察的:
import { Component, OnInit } from '@angular/core';
import { MockDataService } from '../../shared/services/mock-data.service';
import { ObservableInput } from 'rxjs';
@Component({
selector: 'app-iconography',
templateUrl: './iconography.component.html'
})
export class IconographyComponent implements OnInit {
pbiMini$ = this.mockdata.get('pbi-mini-names.json');
constructor(private mockdata: MockDataService) {}
ngOnInit() {}
}
但现在我需要按一个对象键对这些数据进行排序,例如“name”
我已经找过了,我想不出来。在过去,当把JSON作为一个不可观察的普通数组时,我成功地使用了
ngOnInit() {
this.pbiMini.sort((a, b) => a.name.localeCompare(b.name));
}
但它不象我现在这样在可观察的物体上工作。这是怎么做到的
更新
根据一项建议,我试了一下
ngOnInit() {
this.pbiMiniSorted$ = this.pbiMini$.pipe(
map(array => {
return array.sort();
})
);
}
但这无法编译,错误如下:
错误TS2339:类型“Object”上不存在属性“sort”。使用运算符修改Observable中的值
const array$ = of([2, 1, 3]);
const modified$ = array$.pipe(
// map receives a function which receives Array and returns Array
map(array => {
// here you can access to the data as Array object
return array.sort();
}),
);
错误TS2339:类型“Object”上不存在属性“sort”。请声明接口并告诉
get
it<代码>http.get(…)谢谢,但我实在受不了。最后,我只是在Angular之外对JSON文件进行了永久性排序。对于@tsugitta来说,这不是很酷。他给了你正确的答案,就像他说的,你这里只有一个类型的问题。类型是最好的特性之一。它将帮助您创建更健壮的应用程序。这应该是公认的答案
const array$ = of([2, 1, 3]);
const modified$ = array$.pipe(
// map receives a function which receives Array and returns Array
map(array => {
// here you can access to the data as Array object
return array.sort();
}),
);