Lately, I've been working on a settings application with slide toggles. Currently, I have set up local storage to store the toggle state. However, I now want to update the toggle status based on the server response. The goal is to toggle buttons according to values stored in a database. The issue I'm facing is that I can't seem to retrieve the values from the HTTP response. I am able to log the entire response, but extracting specific values has proven to be a challenge. Any assistance would be greatly appreciated. Thank you in advance.
Below is the code snippet:
Component
export class PolicyComponent implements OnInit {
@Output() change: EventEmitter<MatSlideToggleChange>;
@Input() checked: boolean;
isChecked = true;
formGroup: FormGroup;
filteringSchedule: boolean;
toggle: boolean;
policy:Policy[];
constructor(
private formBuilder: FormBuilder,private policyService:PolicyService
) { }
ngOnInit() {
this.filteringSchedule = JSON.parse(sessionStorage.getItem('toggleButtonState'));
this.formGroup = this.formBuilder.group({
enableWifi: this.filteringSchedule,
acceptTerms: [false, Validators.requiredTrue]
});
this.policyService.getPolicy().subscribe(
(response)=>{
console.log(response); })
}
onFormSubmit(formValue: any) {
alert(JSON.stringify(formValue, null, 2));
}
onChange(ob: MatSlideToggleChange) {
this.filteringSchedule = !this.filteringSchedule;
sessionStorage.setItem('toggleButtonState', JSON.stringify(this.filteringSchedule));
}
}
Model:
export class Policy
{
id:number;
policy1:string;
policy2:string;
}
Service:
export class PolicyService {
constructor(private http:HttpClient) { }
baseUrl:string="/policy";
getPolicy()
{
return this.http.get<Policy[]>(this.baseUrl);
}
}
Response is:
[
{
"id": 1,
"policy1": "a",
"policy2": "b"
}
]