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

Converting XML to JSON with the help of XSLT transformation

I am currently working on a project that involves converting XML to JSON using XSLT. Here is a snippet of the XML I am trying to convert: <some_xml> <a> <b> <c foo="bar1"> <listing n="1">a</listing> <list ...

Tips on extracting the value from a nested array in JavaScript

If my array is structured like this: $scope.test = [ ["Invalid Image","file size is invalid"], [], [], [], [] ] Is there a way to extract and display only the values from th ...

``There seems to be a problem with decoding JSON data in Swift, as some information

I am currently working on querying the NASA image API with Swift 4. After testing my network request and decoding setup using JSONPlaceholder, everything was functioning properly. However, when I switched to the NASA API URL and JSON data structure, I enco ...

Different methods to send dynamically created vuejs array data to a mysql database

I'm currently utilizing this code in my LARAVEL project http://jsfiddle.net/teepluss/12wqxxL3/ The cart_items array is dynamically generated with items. I am seeking guidance on looping over the generated items and either posting them to the databa ...

When it comes to form validations, I encounter an issue. I am able to view errors.minlength in the console, but for some reason, I am unable to access it

I would like the message "name is too short" to be displayed if last_name.errors.minlength evaluates to true. However, I encounter an error: Property 'minlength' comes from an index signature, so it must be accessed with ['minlength']. ...

What is the best way to obtain the output of a JavaScript function on the server side?

I'm dealing with a JavaScript function that returns an array in this particular format: <script type="text/javascript"> function looping() { var column_num = 1; var array = []; $("#columns ul").not(" ...

Is there a way to attach a ref to a Box component in material-ui using Typescript and React?

What is the best way to attach a ref to a material-ui Box component in React, while using TypeScript? It's crucial for enabling animation libraries such as GreenSock / GSAP to animate elements. According to material-ui documentation, using the itemRef ...

Failed to retrieve JSON data on the subsequent request using the specified URL

I'm encountering an issue with a function that retrieves and processes JsonData. My current code looks like this: def getData(link,row): u=urllib2.urlopen(link).read(); jsonObject=json.loads(u); # do some stuff return (jsonObject[u&ap ...

Tips for retrieving a child component's content children in Angular 2

Having an issue with Angular 2. The Main component displays the menu, and it has a child component called Tabs. This Tabs component dynamically adds Tab components when menu items are clicked in the Main component. Using @ContentChildren in the Tabs comp ...

Specify the dependencies in the package.json file to ensure that the React package designed for React v17 is compatible with React v18 as well

Recently, I developed an npm package using React v17.0.2. The structure of the package.json file is as follows: { "name": "shoe-store", "version": "0.1.0", "private": true, "dependencies": ...

Converting nested arrays within a JSON object to a CSV format

I am currently utilizing the 'json-csv' library to convert a user's arrays with nested objects and arrays into a CSV format. var users = [ { subscriptions: [ { package : { name: &a ...

What is the proper method for deserializing .NET Dictionary objects with Jackson?

Here's a brief summary before diving into the detailed explanation below :-) I'm looking for help on deserializing a Dictionary using Jackson and a custom deserializer. Currently, I have an Android app communicating with a .NET (C#) server via ...

Angular 2 is throwing an error, stating that Observable is not defined

I'm currently working with Observable and ChangeDetectionStrategy to notify other components about any changes that occur. However, I am encountering an issue where the Observable object addItemStream is coming up as undefined. Can anyone spot what mi ...

Learn how to access tag attributes within the ngIf function in Angular 2

considering this structure <a *ngIf="canAccess()" routerLink="/adminUsers">...</a> <a *ngIf="canAccess()" routerLink="/link2">...</a> <a *ngIf="canAccess()" routerLink="/otherlink">...</a> <a *ngIf="canAccess()" rout ...

The issue with .NET Core - SerializerSettings not taking effect

Configuration.cs services.AddMvc().AddJsonOptions(config => { config.SerializerSettings.NullValueHandling = NullValueHandling.Ignore; }); DataConverter class JsonConvert.SerializeObject(dataObject) The SerializerSettings ...

Reorganize code in JavaScript and TypeScript files using VSCode

Is there a way to efficiently organize the code within a .js / .ts file using Vscode? Specifically, when working inside a Class, my goal is to have static variables at the top, followed by variables, then methods, and so on automatically. I did some resea ...

Having trouble notifying a json object following an ajax request

My project involves using a PHP file that contains an array with multiple values. Additionally, I have an HTML page that features a single input field. A listener is set up to detect changes in the input field. Once a change occurs, an AJAX call is trigge ...

Incorporating Angular supplementary elements into the index.html file

<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>UdemyApp</title> <app-settings></app-settings> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1. ...

injecting a variable from the configuration service into a TypeScript decorator

I am interested in setting up a scheduled task for my NestJs application to run at regular intervals. I found information on how to use intervals in the NestJs documentation. Since my application uses configuration files, I want to keep the interval value ...

Tried to insert an array into JSON, ended up with an unexpected outcome

My formatting skills are lacking, perhaps due to a weak foundation. Here is the json I'm working with: 'first_name'=>'steve', 'msg'=>'something here','profile_id'=>1 I am trying to add a new ...