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

Angular allows for the use of the ngIf condition within nested loops to control the display of

I'm currently working on implementing a navigation side menu using Angular with 3 levels of submenus. Below is the code I have tried: <ul class="nav metismenu" id="side-menu" *ngIf="menulist.length != 0"> <li *ngFor="let menu1 of menuli ...

Troubleshooting the issue of Angular 2 error: Cannot access the 'getOptional' property

Currently, I am navigating my way through angular 2 and attempting to define a service named searchservice. I want to inject this service in the bootstap part of my project: import {SearchService} from 'src/service'; Here is the code for the Se ...

Exploring the TypeScript Type System: Challenges with Arrays Generated and Constant Assertions

I am currently grappling with a core comprehension issue regarding TypeScript, which is highlighted in the code snippet below. I am seeking clarification on why a generated array does not function as expected and if there is a potential solution to this pr ...

When the mat-tree collides with a stylish css grid

Is there a way to transform a lengthy checkbox tree into a more manageable grid layout? The main issue is the lack of grouping wrappers, with only partial padding indicating group relationships. Check out this StackBlitz link for reference It seems that ...

What is the best way to implement a side navigation bar with 100 tabs using Angular 4?

I am new to learning AngularJS and could use some guidance. Currently, I am working on an Angular 4 SPA project that consists of a sidebar with 100 tabs, each containing different content. Here is an image of the sidebar. I have tried a simple approach by ...

Error: Unable to access null properties while attempting to address Readonly property error by implementing an interface

Here is the code snippet I am working with: interface State { backgroundColor: boolean; isLoading: boolean; errorOccured: boolean; acknowledgment: string; } export class GoodIntention extends React.Component<Props, State> { ... onCli ...

Error encountered during conversion from JavaScript to TypeScript

I am currently in the process of converting JavaScript to TypeScript and I've encountered the following error: Type '(props: PropsWithChildren) => (any[] | ((e: any) => void))[]' is not assignable to type 'FC'. Type '(a ...

Is it possible to assign a variable to an Ionic datetime input property?

I am trying to pass a variable, someVar, into the max attribute (input property) of an Ionic 2 (and Angular 2) DateTime component. It seems like it only accepts a hardcoded string such as max="2017-08-31". HTML <ion-datetime displayFormat="DD/MM/YYYY" ...

Leveraging default values in generic implementations

Imagine a scenario where the following code is present: type QueryResult<ResultType = string, ErrorType = string> = { result: ResultType, } | { errors: ErrorType, } So, if I want to initialize my result, I can proceed like this: const myResult: ...

When using Protractor with Typescript, you may encounter the error message "Failed: Cannot read property 'sendKeys' of undefined"

Having trouble creating Protractor JS spec files using TypeScript? Running into an error with the converted spec files? Error Message: Failed - calculator_1.calculator.prototype.getResult is not a function Check out the TypeScript files below: calculato ...

incongruity discovered during string conversion in HmacSHA256 within Ionic framework

I am facing an issue while trying to create a token in IONIC using the CryptoJS library. The signature generated by the method is different from what I expect. The expected signature is lLJuDJVb4DThZq/yP4fgYOk/14d3piOvlSuWEI/E7po= but the method provides m ...

Utilizing personalized Angular component as a feature within OpenLayer map

I am exploring the possibility of integrating my own component as a zoom control for an OpenLayers map. I came across some helpful information here, indicating that it can be achieved by creating specific HTML elements. However, I already have a pre-existi ...

Encountering an error stating "unable to access properties of undefined (reading 'redirectUri')"

I am currently working on fetching details from Okta and saving them in a Store. My code includes an @effect that triggers a service file named a-service.ts. Inside the service constructor, I call the Okta library as shown below: @Injectable() export clas ...

Discuss the communication paths between Server and Client components in the upcoming 14 days

Currently, my objective is to transfer state from a client component to a server component, perform some actions on the server, and then send the updated state back to the client through props. I am in the process of building a booking system using tools ...

Protractor fails to capture the presence of mat-dialog-container

My Protractor test for an Angular 5 application is functioning well, except when it has to handle a popup containing input fields. The HTML element representing the popup looks like this: <mat-dialog-container class="mat-dialog-container ng-tns-c26-5 n ...

Defining TypeScript class events by extending EventEmitter

I have a class that extends EventEmitter and is capable of emitting the event hello. How can I properly declare the on method with a specific event name and listener signature? class MyClass extends events.EventEmitter { emitHello(name: string): void ...

Can you explain the meaning of `(error: T) => void` in error?

I've come across this particular syntax in a few Typescript libraries and I am trying to grasp its meaning. error?: (error: T) => void I have seen it being used like so: class SomeClass { someFunction(error?: (error: T) => void){ } ...

Utilizing geolocation within a promise in Ionic 2

Our implementation of the geolocation call is done within a promise in Ionic 2. It functions properly on iOS and older Android versions. In our app.js file, we are executing the geolocation call and resolving it in the initial view. On Android Marshmallo ...

The page fails to load when redirected, however, it briefly displays the page upon clicking the back button before navigating back to the previous page

Currently, I am working with Angular 2 and encountering an issue when attempting to click on a link. The loading bar continues to progress without displaying the data or HTML content on the page. Furthermore, if I try to go back to the previous page, the i ...

Preventing CSRF, XSRF, and XSS with Angular JWT stored in a Cookie

I'm currently learning Angular and Express, and I am working on implementing a login feature. From what I've gathered, it is recommended to store JWT in cookies with the settings "secure: true" and "httpOnly: true," like so: const jwtBearerToke ...