【发布时间】:2018-01-28 19:59:02
【问题描述】:
我这里有一个 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 中添加一个按钮或其他内容,点击它会调用一个函数来重新排列用户可以在屏幕上看到的项目。目前,仅按问题(按字母顺序、升序或降序)排列 observables 数组的东西就足够了。几个小时以来,我一直在尝试完成此任务,但我在 google(和 stackoverflow)上发现的任何内容都没有帮助我完成此任务。
你们中有人知道如何按照我正在寻找的方式对 observable 的数据进行排序/重新排列吗?
提前致谢。
(如果有帮助,我正在使用 NativeScript + Angular)。
【问题讨论】:
-
我假设在某些时候您将问题数组存储在类的 propertyData 属性中。您粘贴的代码中没有显示。如果是这样,只需创建一些方法并使用 Array.sort 方法重新排序项目。然后从模板中调用这些方法。
-
啊,是的,抱歉。我已经更新了这个问题。我一直在尝试使用array.sort,但我一定是用错了,因为我从来没有引用过这些问题。我以为我会像
this.propertyData.question那样做,但这似乎行不通。
标签: typescript rxjs observable angular2-nativescript