Parsing a JSON array using Moment.js within a subscription function

I have a series of time entries within a data JSON array that I need to parse and format using Moment.js. The formatted data will then be stored in the this.appointmentTimes array for easy access on my view using {{appointmentTime.time}}.

Here is the JSON structure:

[
  { "time":"2018-10-22T14:30:00+0200", "slotsAvailable":1 },
  { "time":"2018-10-22T14:45:00+0200", "slotsAvailable":1 },
  { "time":"2018-10-22T15:00:00+0200", "slotsAvailable":1 }
]

Upon refreshing the page, the following error occurs:

ERROR in src/app/pages/booking/form/booking.component.ts(75,9): error TS2322: Type 'string' is not assignable to type 'object[]'.
src/app/pages/booking/form/booking.component.ts(76,22): error TS2345: Argument of type 'object[]' is not assignable to parameter of type 'string'.

This function is called from my view and handles the corresponding logic:

private appointmentLocations: Array<object> = [];
private appointmentTypes: Array<object> = [];
private appointmentTimes: Array<object> = [];

onChangeTypeId(TypeId) {
    console.log(TypeId);
    this.selectedAppointmentTypeId = TypeId;
    this.apiService
      .getAppointmentTimesById(
        this.selectedAppointmentTypeId,
        this.selectedAppointmentLocation,
        this.selectedDatePicker
      )
      .subscribe((data: Array<object>) => {
        /*this.appointmentTimes = data; */
        this.appointmentTimes = JSON.stringify(
          JSON.parse(data).map(function(data) {
            var pattern = 'HH:mm';
            data = moment(data.time).format(pattern);
            return data;
          })
        );
        console.log(data);
      });
  }
}

Answer №1

Avoid calling .map(response => response.json()) until you subscribe as the response is in string format, not JSON.

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

Javascript loops through a map that contains other maps

At first, I set up the layout like this: <ul id="state_${abbr}"></ul> on the jsp page and now I have to load this JSON map of maps to the layout. coverage.phone.data = { "CA" : { "LOS ANGELES" : "1111", "TORRANCE" : "2222", "S ...

Display a complete inventory of installed typings using the tsd command

How can I display a list of all installed tsd typings in the terminal? Perhaps using the following command: $ tsd list ...

Unable to deserialize the current JSON.Net array in C#

As a programming novice, I still have a lot to learn and would appreciate some guidance! Despite reading through similar posts discussing the same error, I am struggling to find a solution. The error message that I encountered states: Newtonsoft.Json.Js ...

How come only the final file is being saved after reading it into an array?

Currently, I am reading data from a file and storing it in an array. Here is the code snippet: f = new File("some file"); try { s = new Scanner(f); } catch (FileNotFoundException e) { e.printStackTrace(); ...

efficiently populating a 2-dimensional numpy array using python conventions

I'm currently working on populating a 2D numpy array, but I have concerns about scalability with larger array sizes. x=np.array([2,3,4]) y=np.array([1,3,9,13]) mat=np.zeros((x.size,y.size)) for i in range(nx): for j in range(ny): if x[i] > y[j ...

Angular 6: Inconsistent performance of [(ngModel)] functionality

In my Angular 6 project, I am utilizing Bootstrap Modals to implement a specific functionality. Upon clicking the modify button, a modal window should appear with pre-filled values. https://i.sstatic.net/PIg0L.jpg Although I am using template-driven form ...

Verifying Angular Universal Using JSON Web Tokens

I have a project in Angular 10 Universal where I am using JWT obtained from localhost to verify requests for restricted routes. Currently, I am utilizing the following package for authentication: https://www.npmjs.com/package/@auth0/angular-jwt The issue ...

Utilizing JQuery to display JSON data on a data table using Ajax

Seeking guidance on jQuery, I am diving into a new datatable venture with preloaded data. Upon searching, the goal is to update the table by removing existing data and displaying only the search results. My attempt so far includes: app.common.genericAjaxC ...

Is it possible to update only the necessary data using the Update Controller?

Update Controller exports.UpdatePanelMembers = (req, res) => { const { panelId } = req.params; if (panelId) { Panel.findOneAndUpdate( { _id: panelId }, { panelMembers: { member1: { memberId: req.body.pan ...

An issue arises in Typescript when attempting to pass an extra prop through the server action function in the useForm

I am struggling with integrating Next.js server actions with useFormState (to display input errors on the client side) and Typescript. As per their official documentation here, they recommend adding a new prop to the server action function like this: expo ...

Managing AJAX Errors in PHPAJAX error handling tips for developers

My current code is only set up to display a general error message when an error occurs during execution. I want to improve it by returning specific error messages for different scenarios. However, I have not been able to find satisfactory solutions in my s ...

The type of Object.values() is not determined by a union or Records

When utilizing TypeScript, the Object.values() function encounters issues in deducing the accurate type from a union of Records: type A = Record<string, number>; type B = Record<string, boolean>; function func(value: A | B) { const propert ...

Leveraging jest for handling glob imports in files

My setup involves using webpack along with the webpack-import-glob-loader to import files utilizing a glob pattern. In one of my files (src/store/resources/module.ts), I have the following line: import '../../modules/resources/providers/**/*.resource. ...

Converting nested JSON to a repeating CSV file using Powershell

Looking for a solution similar to what was discussed in the thread about converting nested JSON arrays into separate columns in a CSV file, but with a slight twist. Instead of exporting to flattened csv format, I need to export each nested value onto a sep ...

Discover a demonstration showcasing login and registration functionalities by utilizing Flask, SQLAlchemy, Angular, and JSON

Hello everyone, I am new to Flask, SQLAlchemy, Angular, and JSON. Despite being a beginner in these technologies, I am working on building an application that utilizes them. Can anyone kindly share a small demo of a login and registration page with me or ...

Ways to eliminate a comma in a list without resorting to the replace method

I've encountered an issue with my original data containing commas. This data is in the form of a JSON object. When I read a file containing my JSON object using a BufferedReader, I add the output to a list. Although everything seems to be working fi ...

npm encountered an error while trying to update Angular 4

Looking to update Angular2 to Angular 4 and encountering an issue with the following command: npm install @angular/common@latest @angular/compiler@latest @angular/compiler-cli@latest @angular/core@latest @angular/forms@latest @angular/http@latest @angular ...

Troubleshooting issue with alignment in Material UI using Typescript

<Grid item xs={12} align="center"> is causing an issue for me No overload matches this call. Overload 1 of 2, '(props: { component: ElementType<any>; } & Partial<Record<Breakpoint, boolean | GridSize>> & { ...

Initial values are not retained for nested form components upon submission

In an attempt to incorporate nested form components in Angular using reactive forms and ControlValueAccessors, I have been following a helpful guide available at the following link: While most of my implementation is working correctly, I am encountering o ...

Presenting JSON output using AngularJS

I'm struggling to showcase JSON response data using AngularJS Despite able to see the results in DevTools, I am facing issues while displaying them on the screen. Here is the controller code: MovieApp.controller('movieAdminCtrl', ['$ ...