Set the values retrieved from the http get response as variables in an Angular application

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"
    }
]

Answer №1

Based on my observation, it looks like a better approach would be to modify the code as follows:

this.policyService.getPolicy().subscribe(
        response => {
            this.policy = response;
        })

Answer №2

Seems like you're getting close. Remember to store your response in a variable within your component:

export class PolicyComponent implements OnInit {
  serverData: any;

  ngOnInit() {
    this.filteringSchedule = JSON.parse(sessionStorage.getItem('toggleButtonState'));
    this.formGroup = this.formBuilder.group({
      enableWifi: this.filteringSchedule,
      acceptTerms: [false, Validators.requiredTrue]
    });

    // Retrieve policy data from service
    this.policyService.getPolicy().subscribe(
      (response)=>{
        console.log(response);   

        this.serverData = response; // You might want to store specific properties like this.serverData = response.data only;
     })
  }
}

Now you can utilize that variable in your HTML template:

<div *ngFor="let policy of serverData">
  {{policy.policy1}}
  <p *ngIf="policy.policy2"> 
    Another policy available: {{policy.policy2}}
  </p>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to incorporate the async pipe into my codebase when working with GraphQL queries?

I am currently working on an Angular project where I utilize GraphQL to fetch data in my component. In the HTML code, I display an image of the result. However, I encountered an error in the console that said: ERROR TypeError: Cannot read property 'im ...

The Elusive Glitch: IOS Encounter with Ionic 2

VIEW PROBLEM</p> I am currently developing an Ionic 2 application using Angular 2. Interestingly, I have encountered a peculiar issue that only occurs on one specific page of the app, but specifically on IOS devices. Strangely enough, only the visib ...

Preserve your NativeScript/Angular ImagePicker choice or retrieve the complete file path

After choosing an image with the Image Picker, I get a content// URL content://com.android.providers.media.documents/document/image%3A139 However, when using ImageSource.fromAsset(), I receive an empty object. My main objective is to save this image as a ...

The proper approach for managing downloaded d.ts files from DefinitelyTyped after installation through npm

Visual Studio 2017 Enterprise ASP.NET MVC Application TypeScript 2.5 SDK Source control is in TFS I have opted to use Microsoft's built-in property editor instead of creating a custom tsconfig.config file: https://i.sstatic.net/VgcQO.png To streaml ...

What causes the Angular router URL to vary from the document location on reload while employing CanActivate?

My Angular 2 router setup seems to be causing some issues. When I refresh the page, I've noticed that the router object's URL value is different from the location.hash property of the document. For example, when I check router.url, I get "/", bu ...

How can you expand the class of a library object in Animate CC using Createjs?

I am currently in the process of migrating a large flash application to canvas using Typescript, and I'm facing challenges when it comes to utilizing classes to extend library objects. When working with a class library for buttons, class BtnClass { ...

Is it feasible to securely remove an item from an array within an object without the need for any assertions in a single function?

My interest in this matter stems from curiosity. The title may be a bit complex, so let's simplify it with an example: type ObjType = { items: Array<{ id: number }>; sth: number }; const obj: ObjType = { sth: 3, items: [{ id: 1 }, { id: 2 } ...

Angular Kendo UI - How to Rotate X-Axis Labels in a Bar Chart

On smaller screens, I am trying to rotate x-axis labels to prevent overlapping. EXAMPLE <kendo-chart *ngIf="!yearLoader" (seriesClick)="barClick($event)"> <kendo-chart-tooltip format="{0} events"></kendo-chart-tooltip> < ...

Error message "After the upgrade to Angular 15, the property 'selectedIndex' is not recognized in the type 'AppComponent'."

My Ionic 6 app with capacitor has been updated in the package.json file. These are the changes: "dependencies": { "@angular/common": "^15.1.0", "@angular/core": "^15.1.0", "@angular/forms": "^15.1.0", "@angular/platform-browser": "^15.1. ...

What is the best way to dynamically change the main content based on the sidebar option chosen in a React application?

Currently, I am in the process of creating the layout for the page similar to the image provided. When a user selects option A from the sidebar, my goal is to display the corresponding content on the same page without navigating to a new one. This projec ...

"Encountered a type error with the authorization from the credentials provider

Challenge I find myself utilizing a lone CredentialsProvider in next-auth, but grappling with the approach to managing async authorize() alongside a customized user interface. The portrayal of the user interface within types/next-auth.d.ts reads as follo ...

Guide on inserting a date into a MySQL DATETIME column in Angular with Node.js

In my application, I have a date picker component. My goal is to store the selected date in a MySQL database column with the data type of DATETIME. When using Angular, the value retrieved from the date picker is displayed as such: console.log(date.value): ...

Concealing the parent view in Angular 2

I need to hide the above parent view. https://i.stack.imgur.com/CZFTn.jpg Here is my code. Upon clicking any of the boxes, the parent should be hidden and the child should appear. <app-navbar></app-navbar> <div class="cont ...

What are the advantages of combining the website URL and API URL within the Angular service?

When deploying my application in a production environment, I encounter an issue with the URL addresses. The web address is , while the API address is . However, when making a request to the API through Angular, the URLs get concatenated into . This issue d ...

The cross-origin resource sharing configuration has not been implemented

I have SenseNet 7.0.0 and ASP.NET 5.2.3 set up, with my Angular (Typescript) application running on localhost:4200 and the ASP.NET application running on localhost:55064. I followed this tutorial for installing Sensenet and used this tutorial for installin ...

How can you transform a variable into an HTML element using Angular?

Currently, I am working on parsing a JSON file that contains information about various articles. The structure of the JSON file is as follows: { "articles": [ { "id": 1, "title": "<h1>How to install Atom</h1>" }, { ...

Is it possible to retrieve the precise key currently indexed within type declaration?

I am currently working on developing a simple type that would require a nested object key to reference the outer level. For better understanding, let's take an example: const obj = { foo: { name: 'bar', ref: 'foo' // & ...

Retrieve the attributes of a class beyond the mqtt callback limitation

Currently, I am utilizing npm-mqtt to retrieve information from a different mqtt broker. My objective is to add the obtained data to the array property of a specific class/component every time a message is received. However, I'm facing an issue wher ...

Unlock the power of Angular by learning how to access HTML elements using @ViewChild

Within the code, there is a component with HTML: <div class="filter" #filterContainer> In another component, I am listening to the body scroll events and attempting to apply scrollTop to the element #filterContainer: export class SkeletonComponen ...

The type '{ children: ReactNode; }' does not share any properties with the type 'IntrinsicAtrributes'

I have explored several discussions on the topic but none of them have provided a solution to my issue. My objective is to develop a reusable Typography component that resembles the following structure: import React from 'react' import type { Ty ...