我有一个可重用的组件,该组件从JSON文件中获取数据。但是,当这个组件作为子组件在其他组件上使用时,我想显示不同的数据(来自不同的JSON路径)。
示例,我有一个Banana
组件
@UxComponent({
selector: "[banana]",
host: {
class: "bananaClass"
}
})
export class BananaCmp extends BaseMolecule {
public name = "Banana";
public description = "Banana is awesome";
public data: any;
public permittedParams: any = {
// Insert the permitted config parameters (remove this line when done)
};
public ngOnInit () {
this.jsonService.loadData("BananaData").then(
(data: any) => this.data = data
);
}
然后想象一下我想在Banana
组件中使用这个Fruits
组件。
export class FruitsCmp extends BaseMolecule {
public name = "Fruits";
public description = Fruits are healthy!";
public data: any;
public permittedParams = {
// Insert the permitted config parameters (remove this line when done)
};
public config = {
// Insert the default config (remove this line when done)
};
public ngOnInit () {
// Maybe something like this, but I need to make sure only FruitsData.json is being fetched. Not both BananaData & FruitsData
// this.jsonService.loadData("FruitsData").then(
// (data: any) => this.data = data
//)
};
如何正确地做到这一点?
答案 0 :(得分:1)
要使BananaCmp
真正可重用,组件应该不知道数据的来源。但在你的情况下,你可能只想要一个@Input()
然后覆盖这样的默认数据
export class BananaCmp extends BaseMolecule {
public name = "Banana";
public description = "Banana is awesome";
public data: any;
@Input inputData:any;
public ngOnInit () {
if(inputData){
this.data = inputData;
}else{
this.jsonService.loadData("BananaData").then(
(data: any) => this.data = data
);
}
//...
}
或者只是完全删除jsonService部分。
然后您可以使用FruitCmp
中的组件
<banana [inputData]="data"> </banana>
答案 1 :(得分:0)
在可重用组件上设置@Input
。然后在该组件视图选择器上设置一个属性,该属性将从父组件中获取值。该值应包含JSON文件名。
答案 2 :(得分:0)
您可以将数据设为输入属性,并从父组件传递值:
// component.html
<div banana [data]="jsonService.loadData('BananaData') |async" />
<div fruits [data]="jsonService.loadData('FruitsData') |async" />
// component.ts
@Input() data;