Tips for saving a variable in Angular that is being received through a subscription as JSON:

Below is an example of the json I have:

[{"id":"1","date":"2020-02-21","status":"present","studentid":"1"},{"id":"2","date":"2020-02-24","status":"present","studentid":"1"}]

I am struggling to store the date in a variable using Angular when it is being subscribed as an http request. Here is what I have attempted so far:

 date:string=[];
 sendPostRequest()  {

  var options = { headers: new HttpHeaders({ 'Content-Type': 'text/plain' }) };
   var count=0;
  this.http.post("http://localhost/android/Api.php?apicall=getattendance", this.postData,options).
  pipe(map(res =>  res.results || []))

  .subscribe(data => {
   this.date=data['date'];


  });

I would greatly appreciate any assistance as I am new to Angular.

Answer №1

If you are receiving a response in the form of an array, you can convert that response to a date format. Below is a sample code snippet demonstrating how you can extract the date from your response:

date:string=[];
 sendPostRequest()  {

  var options = { headers: new HttpHeaders({ 'Content-Type': 'text/plain' }) };
   var count=0;
  this.http.post("http://localhost/android/Api.php?apicall=getattendance", this.postData,options).
  pipe(map(res =>  res.results || []))

  .subscribe(data => {
   this.date=data.map(ele => ele.date);


  });

Here is an example:

const data = [{"id":"1","date":"2020-02-21","status":"present","studentid":"1"},{"id":"2","date":"2020-02-24","status":"present","studentid":"1"}];

const date = data.map(ele => ele.date);

console.log(date);

Answer №2

Iterate over the JSON data and store it in a new array.

const json = [{ "id": "1", "date": "2020-02-21", "status": "present", "studentid": "1" }, { "id": "2", "date": "2020-02-24", "status": "present", "studentid": "1" }];
const datesArray = [];
json.forEach((item) => {
    datesArray.push({
        date: item.date
    })
})
console.log(datesArray);

Answer №3

To represent your date in string format as a single value, you can declare your date variable as an Array []. Simply define your date as a string variable like so:

date: string = ''; or date = '';

Answer №4

It is crucial to have a good understanding of the structure of your JSON data right from the start. You can make use of various online JSON parsers which are readily available for free:

If you analyze your data after organizing its structure, it will look like this:

[
  {
    "id": "1",
    "date": "2020-02-21",
    "status": "present",
    "studentid": "1"
  },
  {
    "id": "2",
    "date": "2020-02-24",
    "status": "present",
    "studentid": "1"
  }

]

The data consists of an array of objects. Therefore, it is essential to loop through each index of the array and extract the required key-value pairs.

The code provided by @wsc offers valuable insights into handling this task effectively.

Answer №5

The result you receive consists of a series of objects. Assign an empty string to the variable 'date' by typing data:string='';

Then, attempt this: this.date=data[0].date

In case of any errors, make sure to revise accordingly.

Answer №6


    let datesArray: string[] = [];
    
    sendPostRequest()  {
        var options = { 
            headers: new HttpHeaders({ 'Content-Type': 'text/plain' }) 
        };
        
        var count = 0;
        
        this.http.post("http://localhost/android/Api.php?apicall=getattendance", this.postData, options)
            .pipe(map(res => res.results || []))
            .subscribe(data => {
                data.forEach(element => {
                    datesArray.push(element.date);
                })
            });

});

Answer №7

It seems like your query is closely related to some existing questions that have been asked before. If you're looking to save it as a variable, you might find this helpful: Storing API Data in a Variable [Angular]

For converting it into a date format, you can refer to this post: How to Convert Current Date to YYYY-MM-DD Format using Angular 2

UPDATE

This issue may arise from a problem with iteration. An approach like the following should work fine.

Simply loop through your response and add each element to your list:

.subscribe(data => {
  data.forEach((item) => {
      date.push({
          date: item.date
      })
  })
})

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 utilize and display data in a *ngFor loop

I have created a simple service for accessing an HTTP service. Can anyone help me with how to bind this service information in *ngFor? import { Component } from '@angular/core'; import {Http } from '@angular/http'; import { In ...

The generics in TypeScript for Parameters<URLS[T]> and the corresponding URLS[T] are not compatible

In the code below, I am encountering a type error: const urls = { inviteNewUser: ({teamId, intent = 'invite'}: {teamId: string; intent?: Intent}) => `/magic-link?intent=${intent}&teamId=${teamId}`, resetPassword: ({intent = 'r ...

Conceal a row in a table using knockout's style binding functionality

Is it possible to bind the display style of a table row using knockout.js with a viewmodel property? I need to utilize this binding in order to toggle the visibility of the table row based on other properties within my viewmodel. Here is an example of HTM ...

Troubleshooting Jasmine Unit Testing issues with the ng-select library

Recently, I integrated the ng-select component from Github into my Angular application without encountering any console errors during runtime. It functions as expected; however, issues arise when running unit tests with Jasmine. To incorporate NgSelectMod ...

What is the appropriate return type for this function in TypeScript?

Seeking clarity on a fundamental TypeScript concept here. I've noticed that Google Cloud examples use JavaScript, and I'm in the process of converting one to TypeScript. Source: https://cloud.google.com/storage/docs/listing-buckets#storage-list ...

Setting up Angular Toolkit via npm installation

After successfully installing the UIKit npm package within an Angular 2 CLI project, what steps should I take to utilize it? I have also installed typings for UIKit (@types/uikit), but I am unsure of how to properly import the package into a controller i ...

Tips for navigating to a different route during the ngOnInit lifecycle event

How can I automatically redirect users to a specific page when they paste a URL directly into the browser? I would like users to be directed to the /en/sell page when they enter this URL: http://localhost:3000/en/sell/confirmation Below is the code I am ...

Issue: The 'async' pipe was not found after updating to AOT and IVY

I recently upgraded my project to AOT compliance and ever since, I've been experiencing issues with the | async pipe in my HTML code. Here is an example of what my HTML looks like: <div *ngIf="(mySubscription$| async) != null"> //some ...

The function webpack.validateSchema does not exist

Out of the blue, Webpack has thrown this error: Error: webpack.validateSchema is not defined Everything was running smoothly on Friday, but today it's not working. No new changes have been made to the master branch since Friday. Tried pruning NPM ...

retrieving a date from a different source and displaying it in a date

Is there a way to ensure that the date format in an input of type date always follows the dd/MM/yyyy Brazilian pattern, regardless of the computer or browser specifications? <div class="input-group input-group text-center in ...

What is the reason behind Angular not allowing users to define @Output events that begin with 'on'?

While developing a component, I defined an output EventEmitter named onUploaded. However, Angular flagged an error instructing me to use (uploaded) instead. This restriction is due to security concerns, as bindings starting with 'ono' pose risks. ...

The Angular client fails to receive data when the SignalR Core Hub method is called from the Controller

Issue with Angular SignalR Client not Receiving Data from ASP.NET API I have a setup where an angular website is connected to an asp.net back-end using SignalR for real-time data service. Everything was working fine when tested in localhost, but after pub ...

Encountering 'npm install' error while trying to follow the Angular2 5 minute

I encountered an error while attempting to follow the Angular2 5 min quick start guide. Can someone assist me in resolving it? vagrant@vagrant-ubuntu-trusty-64:/vagrant/angular2-tutorial$ sudo npm install <a href="/cdn-cgi/l/email-protection" class=" ...

Keeping the view up to date with changes in an Array in Angular

After extensive research through various posts and Google searches, I have yet to find a solution to this particular issue. I have explored the following two links without success: Angular doesn't update view when array was changed Updating HTML vi ...

Streamlining the deployment process of Angular applications on IIS through automation tools such as Docker and Jenkins

I am currently manually deploying my Angular application on an IIS server by copying the build from my system to a specific location on the server. The code for my application is stored in a TFS repository. My application's backend is powered by Mul ...

What is a more organized approach to creating different versions of a data type in Typescript?

In order to have different variations of content types with subtypes (such as text, photo, etc.), all sharing common properties like id, senderId, messageType, and contentData, I am considering the following approach: The messageType will remain fixed f ...

Connect your Angular project on your local system

Having some trouble connecting my angular 13 project as a ui-component library. Successfully built the project and have the package stored in a dist folder. I then linked it to my primary project (angular 14) using "yarn link" and confirmed its presence as ...

NestJS Exporting: Establishing a connection for PostgreSQL multi tenancy

I have been working on implementing a multi tenancy architecture using postgres. The functionality is all in place within the tenant service, but now I need to import this connection into a different module called shops. Can anyone provide guidance on how ...

Having trouble getting a constructor to function properly when passing a parameter in

Here's the code snippet I'm working with: import {Component, OnInit} from '@angular/core'; import {FirebaseListObservable, FirebaseObjectObservable, AngularFireDatabase} from 'angularfire2/database-deprecated'; import {Item} ...

Error: Uncaught TypeError - Unable to access 'reduce' property of undefined value

Currently, I am focusing on implementing yup validation. Specifically for FileList validation, encountering an issue where leaving the input empty triggers the following error message: enter image description here Below is the code snippet in question: (C ...