Utilizing the get and set methods to alter the structure of a string, but encountering the issue where the set method is

Upon receiving a datetime through an HTTP request, I need to format it before utilizing it. To achieve this, I utilize the get and set methods in my code. However, I noticed that the set method is never invoked.

This is how my component (AdminComponent) looks like:

import { Component, OnInit } from '@angular/core';

import { AdminService } from './admin.service';
import { Config } from './_config';

@Component({
  selector: 'app-admin',
  templateUrl: './admin.component.html',
  styleUrls: ['./admin.component.css']
})
export class AdminComponent implements OnInit {


    config: Config = new Config();

    constructor(private adminService: AdminService) { }

    ngOnInit() {

      this.getConfig();
    }


    getConfig(): void { //THIS IS THE IMPORTANT PART FOR THIS QUESTION
        this.adminService.getConfig().subscribe(config => {
            this.config = config;
            console.log(this.config); //just for debugging
        });
    }
    saveConfig(): void {
        //saving logic goes here
    }

}

The AdminService implementation:

import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { catchError } from 'rxjs/operators';
import { Config } from './_config';

@Injectable({
  providedIn: 'root'
})
export class AdminService {

    private getConfigUrl = '//../getConfig.php';
    private saveConfigUrl = '//../saveConfig.php';

  constructor(private http: HttpClient) {
      this.getConfigUrl = window.location.protocol+this.getConfigUrl;
      this.saveConfigUrl = window.location.protocol+this.saveConfigUrl;
  }


    getConfig(): Observable<Config> {
        var data = ""; //used but not required for this example.
        var headers = new HttpHeaders({'Content-Type': 'application/x-www-form-urlencoded'});
        return this.http.post<Config>(this.getConfigUrl, data, { headers: headers } ).pipe(catchError(this.handleError('admin getConfig', [])));
    }

    saveConfig(config: Config) {
        var data = "config="+JSON.stringify(config);
        var headers = new HttpHeaders({'Content-Type': 'application/x-www-form-urlencoded'});
        return this.http.post<string>(this.saveConfigUrl, data, { headers: headers } ).pipe(catchError(this.handleError('admin saveConfig', [])));
    }



          /**
   * Handle Http operation errors without stopping the app.
   * @param operation - name of the failed operation
   * @param result - value to return upon failure
   */
  private handleError<T> (operation = 'operation', result?: T) {
    return (error: any): Observable<T> => {

      // Send error to logging infrastructure
      console.error(error); 

      // Continue running the app by returning an empty result.
      return of(result as T);
    };
  }
}

Lastly, the Config class which utilizes the get and set methods:

export class Config {
    title: string;
    _startdate: Date;
    enddate: Date;

    public get startdate(): string {
        console.log("get called");
        return this.parseDateToStringWithFormat(this._startdate);
    }

    public set startdate(v: string) {
        console.log("set called");
        let actualParsedDate = v ? new Date(v) : new Date();
        let normalizedParsedDate = new Date(actualParsedDate.getTime() + (actualParsedDate.getTimezoneOffset() * 60000));
        console.log("from: "+v+" to: "+normalizedParsedDate);
        this._startdate = normalizedParsedDate;
    }


    private parseDateToStringWithFormat(date: Date): string {
        return date.toISOString().substring(0,16);
    }
}

I made changes in the getConfig() function of AdminService and accessed variables separately, leading to successful execution. Although effective with fewer variables, this approach may not be suitable for larger classes. The reason behind the initial version not working remains unclear.

Answer №1

It has become clear to me now that the issue lies in not setting anything to it... SET will only be triggered when your code assigns values to it

getConfig(): void { //IT'S CRUCIAL FOR THIS QUESTION
    this.adminService.getConfig().subscribe(config => {
        this.config = config; // this is where you are making a GET request                
        config.startdate = 'foo'; // an example of using SET
        console.log(this.config);
    });
}

UPDATE:
To manage larger code, you can utilize a constructor inside the Config class:

class Config {

    private title: string;
    private startdate: string;
    private enddate: string;

    constructor(title: string, startdate: string, enddate: string) {
        this.title = title;
        this.startdate = startdate;
        this.enddate = enddate;
    }

    // ... getters/setters
}

I believe this is the most effective way to utilize classes in TypeScript

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

Why isn't the table in the select query updating after an insert query is executed in Express?

Seeking assistance! Currently, I am delving into express and typescript. I have encountered an issue where the table from a select query does not update after an insert query when rendering a view. Strangely, the data in the table remains unchanged (showin ...

What exactly is the purpose of the colon in JavaScript's import statement?

Looking at the following example. import { QueryClientContract, TransactionClientContract } from '@ioc:Adonis/Lucid/Database' I am puzzled by the use of colons and I am unsure about where the imported files are being referenced from. ...

Resizing svg to accommodate a circle shape

As I work on my vue.js app that involves a plethora of diverse icons, I made the decision to create a small icons builder in node.js. The purpose is to standardize their usage and also "crop" each SVG so it fits perfectly within its parent container by uti ...

Encountering an Angular error while trying to use the command "npm run dev:ssr" to observe server-side rendering on the localhost

When I run this command, it starts listening on port 4200 but the page keeps loading without ever fully loading and shows this error in the command prompt: Unhandled Promise rejection: connect ECONNREFUSED 127.0.0.1:6379 ; Zone: <root> ; Task: Promis ...

Update the styling of buttons in CSS to feature a unique frame color other

Can anyone help me with styling Bootstrap buttons and removing the blue frame around them after they're clicked? Here's what I've tried: https://i.stack.imgur.com/jUD7J.png I've looked at various solutions online suggesting to use "ou ...

What is the most efficient way to apply multiple combinations for filtering the information within a table?

I'm facing an issue with my Angular project. I have 4 select boxes that allow users to apply different filters: office worker project name employee activities The problem I'm encountering is the difficulty in predicting all possible combination ...

Encountering a 401 Error while trying to host an Angular app on Google Cloud Storage

I am currently facing an issue with deploying my Angular app to a Google Cloud Storage bucket. The bucket is public and set up to be served as a custom website via CNAME (test.example.com). The main page and 404 handler are mapped to index.html, but I am e ...

Enhance Your Search Functionality with an Angular Pipe

I created a custom pipe that filters the search field and displays a list of items based on the search text. Currently, it only filters by companyDisplay, but I want to also filter by companyCode and companyName. JSON [{ companyDisplay: "ABC", co ...

Dealing with Angular State Management Across Components (Direct Dependency): encountering a NullInjectorError - R3InjectorError

I have encountered a NullInjectorError in my Angular application and I am seeking assistance in resolving it. To provide context, my application consists of three main components: ProductRegistrationAndListingScreen, ProductList, and ProductRegistration. ...

The main source for loading the 'XYZComponent' cannot be located

There's an issue I'm facing where ng2 code is being loaded into a .Net MVC component, but the console is showing the following error: EXCEPTION: Uncaught (in promise): Error: Cannot find primary outlet to load 'UsersComponent' Error: C ...

Responding to modifications occurring beyond the Angular2 framework

I have a traditional non-angular web page built with basic JavaScript, and I am interested in integrating Angular2 for some new functionalities. My idea was to bind an Angular2 component to an object being updated by the existing JS code, allowing Angular2 ...

The combination of Observable streams in combineLatest will persist even if one encounters a

I have a function designed to retrieve multiple documents from Firebase. fetchDocuments(documentIds: string[]): Observable<TreeNodeDocument[]> { const observables = []; for(let id of documentIds){ observables.push(this.fetchDocument( ...

Using TypeScript, creating a tagged template literal for running Jest tests with the `test.each`

Struggling to construct a jest test.each with a tagged template literal test.each` height | text ${10} | ${undefined} ${20} | ${undefined} ${10} | ${'text'} ${20} | ${'text'} `('$height and $text behave as expected&a ...

Tips for initializing an Angular 2 application using asynchronous methods

If you're looking to bootstrap an Angular 1 application asynchronously, there's a great resource on how to do it. This method allows you to fetch a JSON file from the server before the application is fully loaded. Here is the main code snippet: ...

Integrating router-outlet into Angular 2 component affects ngModel functionality

Currently, I am experimenting with angular 2 beta 9 and have encountered an issue that I would like some help with. In my component, I have bound an input field using the following code: [(ngModel)]="email" (ngModelChange)="changedExtraHandler($event)" ...

Exploring Angular: How does Number.isNaN handle non-empty strings?

Within my component, there is a dropdown menu that allows users to choose a value. Upon selecting an item from the dropdown, a function called onDropdownChange is triggered. The parameter passed to this function can either be a string ("Please select an op ...

Is there a way to determine if a React functional component has been displayed in the code?

Currently, I am working on implementing logging to track the time it takes for a functional component in React to render. My main challenge is determining when the rendering of the component is complete and visible to the user on the front end. I believe t ...

Guide on how to update an array within typed angular reactive forms

I'm currently working on finding a solution for patching a form array in a strongly-typed reactive Angular form. I've noticed that patchValue and setValue don't consistently work as expected with FormControl. Here's an example of the fo ...

What is the best way to implement a hover effect on multiple rows within an HTML table using Angular?

I am currently working on developing a table preview feature to display events. I previously sought assistance here regarding positioning elements within the table and successfully resolved that issue. Applying the same principles, I am now attempting to c ...

Creating a function that is accessible to the entire module

Creating a universal function in a file that is not a module: example.ts: function example() {} You can easily call this function from another file, say test.ts, without needing to import the function from example.ts: test.ts: example(); // calling univ ...