ivanasetiawan ivanasetiawan - 3 years ago 198
JSON Question

How to show different JSON data on a component in Angular4?

I have a reusable component, this component fetches a data from a JSON file. However, I'd like to show different data (from different JSON path) when this component is used on other components as a subcomponent.

Example, I have a

Banana
component

@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
);
}


Then imagine I'd like to use this
Banana
component inside
Fruits
component.

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
//)
};


How to do this properly?

Answer Source

To make your BananaCmp truly reusable, the component should have no idea where the data is coming from. But in your case, you probably just want an @Input() then override the default data something like this

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
        );
   }
//...
}

Or just remove the jsonService part completely.

Then you can use the component in your FruitCmp like this

<banana [inputData]="data"> </banana>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download