"Working with Typescript: Utilizing a specific attribute in a response to assign data to a table data source

I am working on a straightforward typescript function to retrieve a list along with its status, and my model is defined as follows:

export interface CashPaymentModel  {
  success: boolean;
  data: CashSpendAdHocDTO[];
}
export interface CashSpendAdHocDTO  {
  dueDate: string;
  gross: string;
  moveStageName: string;
  paidDate: string;
  service: string;
  status: string;
  timestamp: string;
  type: string;
}

This is how my service method looks like:

getCashPayments(policyVersionId: number, employeeId: number): Observable<CashPaymentModel> {
    return this.http.get<CashPaymentModel>(`/api/v1/policy/configuration/versions/${policyVersionId}/details?employeeId=${employeeId}`);
  }

Now, I need to display the list from the response (the second attribute in the response) in a table within the template. How do I assign this table's data source?

tableDataSource: Observable<CashPaymentModel>;

testMethod() {
    this.tableDataSource = this.cashPaymentService.getCashPayments(this.policyVersionId, this.employeeId).subscribe((data: CashPaymentModel) => {
      this.tableDataSource = data; .......BLA BLA BLA
    });
  }

Could you help me understand how to correctly assign tableDataSource from the second attribute of the response in TypeScript?

Answer â„–1

If you take a look at your interface layout, you might want to consider implementing the following code snippet:

testMethod() {
    this.tableDataSource = this.cashPaymentService.getCashPayments(this.policyVersionId, this.employeeId).subscribe((data: CashPaymentModel) => {
      this.tableDataSource = data.data;
    });
}

Answer â„–2

To improve handling of responses, start by filtering out undefined ones and assigning the tableDataSource to the data attribute of response in case of a successful result (based on your interface).

Consider implementing the following approach:

tableDataSource: Observable<CashPaymentModel>;

testMethod() {
    this.tableDataSource = this.cashPaymentService.getCashPayments(this.policyVersionId, this.employeeId).pipe(
      filter(res => res !== undefined),
    ).subscribe((res: CashPaymentModel) => {
      if (res.success) {
        this.tableDataSource = res.data;
      } else {
        // handle false success
        // it's recommended not to return 200 response code for false successes and manage them in the 
        // error block of the subscription
      }
    });
  }

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

Using `getElementById` within the Vue.js `mounted` lifecycle hook can sometimes return null

Every time I attempt to retrieve the contents of an id using document.getElementById, I keep receiving a value of null. Below is a snippet of the code: <input-layout v-if="edit" label="Status" class="grayout"> &l ...

Tips for adjusting the angle in SVG shapes

I have designed an svg shape, but I'm struggling to get the slope to start from the middle. Can someone please provide assistance? <svg xmlns="http://www.w3.org/2000/svg" fill="none"> <g filter="url(#filter0_b_1_2556)"&g ...

Stop the execution of javascript code based on the screen width

On my website, I have two menus located in different sections of the page. One menu is shown when the screen width is greater than 555px, while the other menu appears when the screen width is less than or equal to 555px. Although the menus are essentially ...

Protractor: What is the best way to retrieve the baseUrl from the command line input?

How can I retrieve the baseUrl that was passed through the command line in Protractor? For example: protractor conf.js --baseUrl=http://myawesomesite.com I attempted to use browser.baseUrl to access the baseUrl set in my conf.js file, but it does not see ...

Tips for storing data from a table using a button

I have implemented a data table to display information from a database. I am looking for a way to save user information whenever they export data in Excel, CSV, or PDF format from the table. I have already created a function to handle saving user data, but ...

A guide to updating nested properties within MongoDB with the help of Express

In my MongoDB database, I have stored information about the movie "Amazing Spider Man 2": { "title": "Amazing Spider Man 2", "description": "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry&ap ...

What is the best way to incorporate JSON data in my ejs template?

I have encountered an error while trying to display JSON data. Can someone assist me with resolving this issue, please? Error -- > Unexpected token ; in "/home/ubuntu/workspace/project_guest_book/views/pages/posts.ej Below is the code that is caus ...

Move the creation of the HTML string to an HTML template file within ngx bootstrap popover

I have incorporated ngx bootstrap in my project through this link To display dynamic HTML content in the popover body, I am using a combination of ngx-bootstrap directives and Angular template syntax as shown below: <span *ngFor="let item of items;"&g ...

Creating a personalized 404 page in your Angular Project and configuring a route for it

I am currently working on an Angular project that includes a component named 'wrongRouteComponent' for a custom 404 page. Whenever a user enters a non pre-defined route, the 'wrong-route.component.html' should be displayed. However, I a ...

Dynamically insert the ng-if attribute into a directive

In my code, I have implemented a directive that adds an attribute to HTML elements: module1.directive('rhVisibleFor', function ($rootScope) { return{ priority: 10000, restrict: 'A', compi ...

Failure to validate two dates, even when they are both in date format within AngularJS

Although it may seem silly to ask, I am confused as to why this is not working. Even though all the values appear fine in debug mode. My goal is to display an error if the productionStartFrom date is before the current date. Controller scope.currentDate ...

Ways to restrict the maximum length in Draft.js

Is there a way to control the maximum number of characters in draft js? I know how to get the length of the state, but is there a method to prevent the component from being updated past a certain point? var length = editorState.getCurrentContent().getPla ...

Error: Unable to access the 'registerControl' property of the object due to a type mismatch

I'm struggling to set up new password and confirm password validation in Angular 4. As a novice in Angular, I've attempted various approaches but keep encountering the same error. Seeking guidance on where my mistake lies. Any help in resolving t ...

Incorporating a new method into the Object prototype to provide universal access across all modules

I've been delving into Typescript experimentation and I'm attempting to enhance the Object prototype by adding a property that can be accessed by all objects within my modules. Here's what I've developed so far: In a Common.ts file O ...

What is the most effective method for obtaining data from a user and transmitting it to the game's processing system?

[Lance] Seeking the most effective way to extract information from a listener and transfer it to the game engine. Currently working on making the Spaceship follow my mouse movements. I have created a MouseControls.js file that listens for mouse movement an ...

What are the reasons behind my item not triggering an alert even after I have created it, saved it, and attempted to alert it?

I am currently working on a code that allows users to input information which is then stored in an object. However, despite my efforts, when I attempt to retrieve the saved object by alerting one of its values, it indicates that the object does not exist. ...

What is the process of adding an array into a JSON object using the set() function in Firebase?

I am trying to add a new item to my firebase database with a specific JSON object structure: var newItem = { 'address': "Кабанбай батыр, 53", 'cityId': 1, 'courierName': "МаР...

The ion-chip close function activates upon closure, while the ion-item button event is

While trying to utilize an ion-item as a button, I encountered an issue where an ion-chip with a delete event was triggering the ion-item event instead of the intended ion-chip event. Even when using event.stopPropogation, the problem persisted. Is there ...

removing duplicate items from an array in Vue.js

I created a Pokemon App where users can add Pokemon to their 'pokedex'. The app takes a pokemon object from this.$store.state.pokemon and adds it to this.$store.state.pokedex. However, users can add the same pokemon multiple times to the pokedex, ...

Customize the background colors for events in the jQuery weekcalendar plugin to distinguish between different types of activities

I recently started using the jQuery weekcalendar plugin to display a web-based calendar with appointments. The CSS code below is used to set the color of all events: .wc-cal-event { background-color: #00BFFF; font-size: 0.8em; position: absolu ...