我有两个json文件。其中一个包含一个主要颜色对象,另一个json文件包含一个辅助颜色对象数组。有两个按钮我想在两个文件之间切换并显示他们的数据。所以我必须更改路径的文件名以显示其他json的数据。
例:
获得( '../../资产/数据/ primarycolors.json')
用户点击按钮和路径更改为:
获得( '../../资产/数据/ secondarycolors.json')
我有一个带有侧面菜单的Ionic 3应用程序。按钮位于此侧面菜单中。当用户单击其中一个时,将调用函数changeColors('name')。
app.html
<button (click)="changeColor('P')">Primary</button>
<button (click)="changeColor('S')">Secondary</button>
该函数如下所示:
app.component.ts
changeColor(name) {
this.restProvider.changeColorJson(name);
}
如您所见,我正在调用this.restProvider中的函数
这是函数,我正在更改我想要的json文件。
rest.ts
jsonFile = 'primarycolors.json';
.
.
.
changeColorJson(name) {
if(name === 'S'){
this.jsonFile = 'secondarycolors.json';
this.getDataFromJson();
}
else {
this.jsonFile = 'primarycolors.json';
this.getDataFromJson();
}
}
getDataFromJson() {
return new Promise(resolve => {
this.http.get('../../assets/data/' + this.jsonFile) //here should be the path with the correct file
.subscribe((data) => {
resolve(data);
console.log(data);
}, err => {
console.log(err);
});
});
}
最后但并非最不重要的是,html和typescript文件,我在那里显示颜色名称。在这个Typescript文件中,我还调用了getDataFromJson()函数,您可以在上面看到它。
colors.html
<div *ngFor="let color of colors">
<p>{{color.name}}</p>
</div>
colors.ts
colors: any;
.
.
.
getData() {
this.restProvider.getDataFromJson() //the same function from above
.then(data => {
this.colors = data; //adding the data I got from json to colors
});
}
现在我的问题:正如你所看到的,我首先将变量jsonFile(在rest.ts中)设置为'primarycolors.json',因为我希望默认为主色。所以这样可以显示原色,但是当我点击按钮显示次要颜色时,没有任何变化。我认为原因可能是,因为我也在colors.ts中调用getDataFromJson()然后它不会刷新并显示新数据。
所以基本上我的问题是,我如何更改我的代码,以便我可以在两个文件之间切换并显示正确的数据?
你的问题有两点
首先,请检查您是否获取正确的参数值,并确认在获取默认值后再次调用app.component.ts中的方法。
其次,在您单击按钮时的问题中,它可能会从您所需的json文件中获取数据。但可能没有正确分配给你的对象
this.colors = data;
您必须通过HttpGet调用获取数据后验证它应该分配给您所需的对象。看起来您没有为您的对象分配json值。