Creating a custom property in TypeScript and implementing it with an anonymous object: A step-by-step guide

I have implemented a custom getDate() method in my Angular component

getDate(date: Date){
    return date.format("dd-MMMM-yyyy HH:mm").toString();
}

I am retrieving string JSON data from the database in the following format:

`

 "{"field":"date","oldValue":"Mon Mar 25 00:00:00 GMT 2019","newValue":"Tue Mar 26 00:00:00 GMT 2019"},  {"field":"techniqueType","oldValue":"Intra","newValue":"Intralesional"}

`

The getList method in my code looks like this:

    getList(patientId?: number, pageNo?: number) {
       const auditTrailSubscription = 
         this._auditTrailService.getAuditTrailUrl(patientId, pageNo, 
         GridConfig.ITEMS_PER_PAGE)
          .subscribe(
            result => {
            try {
              this.results = [];
              this.totalItems = result.recordsCount;
              this.auditTrailList = result.lstRecords;
              this.auditTrailList.forEach(x => {
              let jschanges = JSON.parse(`[${x.jsonChanges}]`);
              jschanges.forEach(z => {
                this.results.push({
                  userName: x.userName,
                  timestamp: x.timestamp,
                  entityName: x.entityName,
                  field: z.field,
                  oldValue: z.oldValue instanceof Date ? 
                        this.getDate(z.oldValue) : z.oldValue,
                  newValue: z.newValue instanceof Date ? 
                     this.getDate(z.newValue) : z.newValue
                });
              });
            });
          } catch (e) {
            console.log(e);
          }
        },
        err => {
          this.handleError(err);
        }
      );

    this.addSubscription("auditTrail", auditTrailSubscription);
  }

Html file

    <tr *ngFor="let at of results | paginate: { itemsPerPage: 
         _ITEMS_PER_PAGE, currentPage: crtPage, totalItems: totalItems }"
        [attr.data-row-id]="at.userId">
        <td>{{ at.userName }}</td>
        <td>{{ at.timestamp ? (at.timestamp | date: 
        AUDIT_TRAIL_DATE_TIME_FORMAT  ) :  'Unknown' }}</td>
        <td>{{ at.entityName }}</td>
        <td>{{ at.field | titlecase  }}</td>
        <td>{{ at.oldValue }}</td>
        <td>{{ at.newValue }}</td>
      </tr>

In order to handle different types for `oldValue` and `newValue`, I utilize my custom getDate() method to ensure proper formatting.

Answer №1

When working with the Angular HttpClient in your AuditTrailService, it's recommended to create a specific interface for handling JSON HTTP responses. You could define something like this:

interface AuditTrailResponse {
    recordsCount: number;
    lstRecords: AuditTrailRecord[];
}

Then, when making a request in your AuditTrailService, use the following syntax:

this.httpClient.get<AuditTrailResponse>('the/url/of/your/endpoint', { your: params })

By doing this, the variable result will be of type AuditTrailResponse, providing more clarity compared to using any.

I'm not entirely clear on the part where you're converting an interpolated string to JSON. From what I know, JSON.parse() doesn't return Date objects, so the check for oldValue instanceof Date further down shouldn't return true.

However, you can define another interface like this:

interface JSChange {
    userName: string;
    timestamp: number;
    entityName: string;
    oldValue: string | Date;
    newValue: string | Date;
}

If you're confident that your z argument follows this structure, consider casting it to this interface for better type safety.

Answer №2

One way to determine if a date string is valid is to use the Date.parse() method. Simply pass your date string into Date.parse() and check if it returns a number. Here's an example:

if(isNaN(Date.parse("Tue Mar 26 00:00:00 GMT 2019"))){
     console.log("Invalid Date");
}
else {
    console.log("Valid Date")
}

Another approach

var isDateValue =  (new Date(date) !== "Invalid Date") && !isNaN(new Date(date));

Give it a try and let me know how it goes!

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

Ways to update the hidden field's value within a foreach loop when the change event occurs?

On my page, I have input fields and foreach conditions set up. <form action="process.php" name="employee" method="post"> <input type="text" name="name" class="onchangefield"> < ...

When dynamically accessed, the property of a JSON object is considered "undefined"

I'm running into trouble trying to access properties of a JSON object in my JavaScript code using obj[varWithPropName]. Strangely, it does work when I use obj["PropName"]. Here's a simplified snippet for reference: import * as CharInfo from &ap ...

Is it possible to utilize Angular's structural directives within the innerHtml?

Can I insert HTML code with *ngIf and *ngFor directives using the innerHtml property of a DOM element? I'm confused about how Angular handles rendering, so I'm not sure how to accomplish this. I attempted to use Renderer2, but it didn't wor ...

Allow users to zoom in and out on a specific section of the website similar to how it works on Google Maps

I am looking to implement a feature on my website similar to Google Maps. I want the top bar and side bars to remain fixed regardless of scrolling, whether using the normal scroll wheel or CTRL + scroll wheel. However, I would like the central part of the ...

Modifying the Trim Function in AngularJS

Using AngularJS version 1.5.6, I encountered a bug in my large application due to the default behavior of trimming input for text type inputs. Wanting to change this behavior globally without manually updating every textarea and text input element, I am se ...

Is it possible to override values set in the constructor(props) in React? If not, what is the best way to set defaults that can be overwritten later?

I'm confident I know the solution to this problem because my setState({}) seems to have no effect. This is the constructor code that I currently have: constructor(props) { super(props); this.state = { percentiles: { incN ...

Angular styling for input elements that are in the pristine state

Hey there, I'm working with a CSS class that applies a red border to an input field when it is required and invalid, and changes to green when it becomes valid. CSS .ng-valid[required], .ng-valid.required { border-left: 5px solid #42A948; /* green ...

What is the best way to link my PHP variable to a JavaScript variable within a While loop?

My goal is to create a website that retrieves information from a MySQL database and displays pictures upon clicking a button. echo "<img align=\"left\"src=\"".$path[$y]."\" alt=\"error\">"; echo "<img align=\"r ...

I am looking for a string with this particular format in JavaScript

I am working with a JSON string array that looks like this: var dataMaster = [ {"id":1,"name":"John Doe","age":30}, {"id":2,"name":"Jane Smith","age":28} ] If you want to see how I would like to transform this data, please visit the following lin ...

Trigger the C# Click event with JavaScript fire function

Hi there, I could use a bit of assistance. My goal is to allow users to log in by hitting the "Enter" key on their keyboard. While I've successfully detected when the "Enter" key is pressed in my JavaScript code, I'm struggling with how to call m ...

Transform straightforward JavaScript code into jQuery

I'm relatively new to the world of JS and jQuery, and I have a simple working JS function that I would like to convert into jQuery. By doing this, I believe it will enhance my understanding of the inner workings of jQuery (although I already have a ba ...

When Angular 14 application is opened for the first time, the 404 Error Page will automatically appear

I recently developed a small Angular application and I'm now working on creating a custom 404 Error Page for it. The idea is that if a user enters an incorrect URL, the Error page should automatically appear. To achieve this, I have taken the followi ...

Looping Angular Components are executed

I am currently developing an Angular application and encountering an issue with my navbar getting looped. The problem arises when I navigate to the /home route, causing the navbar.component.html components to duplicate and appear stacked on top of each oth ...

Expanding application size by incorporating third-party libraries in NPM and JavaScript

My friend and I are collaborating on a project. When it comes to programming, he definitely has more experience than I do, considering I've only been coding for a little over a year. I've noticed that he prefers building components and function ...

JavaScript Array data value

When working with data retrieved from an interface, I need to extract specific values for a particular menu. How can I efficiently achieve this using JavaScript? [ { "title": "11-07 - 11-08", "weekhit": "Weekhit from 11 ...

The Jasmine test in my Angular project is experiencing a timeout issue, displaying the error message "Async callback was not invoked within 5000ms", despite the fact that no async function is being used in the

Reviewing the source code: import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { IonicModule } from '@ionic/angular'; import { HomePage } from './home.page'; import { LevelGridComponent } from &a ...

Overlaying a div on top of an iframe

Struggling to make this work for a while now. It seems like a small issue related to CSS. The image isn't overlaying the IFrame at the top of the page as expected, it's going straight to the bottom. Here is the code snippet: .overlay{ width: ...

Issue encountered: Nuxt 3 fails to locate the useRoute import

Recently, I updated to the latest version of Nuxt and encountered an issue with the useRoute method. Even though it works, I keep getting a "Cannot Find name useRoute" error message. Can anyone help me figure out what might be missing? <script lang=&quo ...

What are the steps for applying logic based on the types of keys and values in a Map<K,V>?

When it comes to serialization, one must analyze and handle different Map<K,V> types by determining logic based on the key and value types. But how can this be achieved in Typescript? For example: const stringAndNumberPairs: Map<string, number> ...

Angular 2, Utilizing Enum Events

Can someone assist me with hiding the value 2 of the "Titulo" enum and making it visible when I click on the "no" (1) value of the radio button "existio contacto" in coincidence.component.html? This is the HTML for Coincidence: <div class="row"> ...