我这里有一个 JSON 文件,如下所示:
[
{
"question": "What is your age range?",
"options": ["10-20","20-30","30-40","40-50"]
},
{
"question": "How did you find us?",
"options": ["Friend recommendation","Google","Other"]
},
{
"question": "Are you interested in etcetc?",
"options": ["No","Yes","Meh"]
}
]
在我的项目中,我有一个具有相同结构的模型,如下所示:
export interface Test {
question: string;
options: string[];
}
在我的服务文件中,我像这样读取文件(将其转换为可观察的,因为我希望能够更改数据的顺序,并可能稍后添加/删除/更改问题):
getSurveyQuestion(): Observable<Test[]> {
return this.http
.get<Test[]>("/path/to/questions.json")
.do(data => console.log("All : " + JSON.stringify(data)))
}
在控制台中,以上输出:
JS: 全部 : [{"question":"您的年龄范围是多少?,"options":["10-20","20-30","30-40","40-50"]}, { //.....}]
我的组件文件如下所示:
export class TestComponent implements OnInit {
propertyData: Test[] = [];
constructor(private router: Router, private testService: TestService) {}
ngOnInit() {
this.testService.getSurveyQuestion().subscribe(data => {
this.propertyData = data;
}, err => {
console.log(err);
})
}
}
在我的 html 中,我将其输出到屏幕,如下所示:
<StackLayout *ngFor="let item of propertyData">
<Label text="{{item.question}}"></label>
</StackLayout>
现在,我想在 html 中添加一个按钮或其他内容,点击后会调用一个函数来重新排列用户可以在屏幕上看到的项目。目前,简单地按问题排列可观察数组(按字母顺序、升序或降序)就足够了。我已经尝试了几个小时来完成这个任务,但我在谷歌(和 stackoverflow)上发现的任何东西都没有帮助我完成这个任务。
你们中有人知道如何按照我正在寻找的方式对可观察数据进行排序/重新排列吗?
提前致谢。
(如果有帮助的话,我正在使用 NativeScript + Angular)。