Situation : I'm using a data service in my project to get local json data then share it to multiple components. In part of my project, i have a component which is calling another component. The first component is step component, this one get only data with type of steps from json to show them as angular material stepper.. The second one is form component which is responsible of getting each step data by stepId and the step name then load them in each step. I want to add delete/add steps in step component and update data so the second component updates data too but when i do the data service isn't updating... I was getting data from a local json file then i changed it and used "Angular json-webservice" but it's not working, here is the code :
setControls (controls: IControl[]) {
console.log('patch : ',controls)
this.http.post('http://localhost:3000/controls',controls);
}
Question : How to update Angular json-server data in my data service ? If not possible without backend should i pass the array from comp1 to comp2 ? Or initializing an array list an fill it from json file, make the array public static and use it in all components until working on back-end ? (I'm a front-end developer only now)
Update : I followed @Inesa Toroyan reply and put the http.get data into an array in my data service and in my components i get that data array. Adding a new step is working fine but the initial data aren't showing ! The FormGoup and the FormArray are getting the array just before it is filled with the data by http.get() How to fix this ?
Stepper Component :
public inputdataList:{}[]=[]
inputForm!: FormGroup;
constructor(private fb:FormBuilder,private dataService:DataService ){
this.inputdataList =this.dataService.getControls()
this.inputForm = this.fb.group({
inputs: this.fb.array(this.inputdataList) ,
XXXXXXXXX : new FormControl('', Validators.required)
})
}
Data Service :
@Injectable({
providedIn: 'root'
})
export class DataService {
controls: IControl[] = [];
private API_URL= environment.baseURL;
constructor(private http: HttpClient) {
this.http.get<IControl[]>(this.API_URL+'controls').subscribe(
(response) => {
console.log(response)
this.controls =
JSON.parse(JSON.stringify(response)).controls
});;
}
getControls () {
return this.controls;
}
setControls (controls: IControl[]) {
console.log('patch : ',controls)
this.controls = controls;
}
}
I recommend you doing the following.
@Injectable({providedIn: 'root'})Also, I would recommend you to change a bit this part -
this.http.post('http://localhost:3000/controls',controls);You can add the
http://localhost:3000/controlsto your environment.ts file,because later changing it manually in many places will be a very inefficient task.If I got your question incorrectly, please make it more clear :))