Utilizing Smart Table for Data Binding with JSON Dataset

I need help binding a JSON file to a smart table. How can I use the loop function for iteration? The design of the smart table is displaying, but the data from the JSON file is not binding.

Here is the JSON file:

[
{
        "year": 2013, 
        "id": "", 
        "doctor": "Dr. Smith", 
        "illness": "Flu", 
        "apptdate": "3/12/2013",
"details":"Patient had flu for 5 days. No medicines prescribed"
}
]

I am trying to retrieve the data using:

@Injectable()
export class SmartTablesService {
  constructor(private http: Http) {
    
        }
        smartTableData = [];
loadData() {
  console.log('loadData');
   this.http.get('http://192.168.0.100:8000/medical')

.subscribe((data) => {
          setTimeout(() => {
              var contactData = [];
              $.each(data.json(), function (key, value) {
                  var tempData = value.source;
                  contactData.push(tempData);
              });
              this.smartTableData = contactData;
          }, 1000);
      });
}
getData(): Promise<any> {
  console.log("Promise");
  this.loadData();
  return new Promise((resolve, reject) => {
      setTimeout(() => {
          console.log(this.smartTableData);
          resolve(this.smartTableData);
      }, 3000);
  });
}
}

    constructor(private http: Http) { }
       getComments() {
        
       return this.http.get('http://192.168.0.100:8000/article' )
          .map((res: Response) => res.json())
          .catch((error:any) => Observable.throw(error));
       }
}

This is the component section:

@Component({
  selector: 'new',
  template: '<ng2-smart-table [settings]="settings" [source]="source"></ng2-smart-table>'
})
export class NewComponent {
    query: string = '';
    
      settings = {
        noDataMessage: 'Loading...',
       columns: {
        year: {
            title: 'YEAR',
            type: 'string'
          },
          id: {
            title: 'ID',
            type: 'string'
          },
          doctor: {
            title: 'DOCTOR',
            type: 'string'
          },
          illness: {
            title: 'ILLNESS',
            type: 'string'
          },
          apptdate: {
            title: 'APPTDATE',
            type: 'string'
          },
          details: {
            title: 'DETAILS',
            type: 'string'
          }
      }
      };
    
// data

source: LocalDataSource = new LocalDataSource();
constructor(protected service: SmartTablesService){
  this.service.getData().then((data) => {
    this.source.load(data);
  });
}  
}

If anyone knows how to bind it, please help!

Answer №1

Make a simple adjustment to the subscription section on the service page to

var updatedData = value;

thus, .subscriber will appear as

.subscribe((data) => {
          setTimeout(() => {
              var contactInfo = [];
              $.each(data.json(), function (key, value) {
                  var updatedData = value;
                  contactInfo.push(updatedData);
              });
              this.smartTableData = contactInfo;
          }, 1000);
      });
}

This method is successful..!

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

`Trigger a page reload when redirecting`

Currently, I am tackling some bug fixes on an older Zend Framework 1.10 project and encountering difficulties with redirection and page refresh. The issue: The task at hand is to make an AJAX call, verify if a person has insurance assigned, and prevent de ...

What is the best way to manage user sessions for the Logout button in Next.js, ensuring it is rendered correctly within the Navbar components?

I have successfully implemented these AuthButtons on both the server and client sides: Client 'use client'; import { Session, createClientComponentClient } from '@supabase/auth-helpers-nextjs'; import Link from 'next/link'; ...

Access previous value in Vuejs onchange event

In the code snippet below, how can I retrieve the previous value of the model that has been changed, specifically the age in vuejs? var app = new Vue({ el:"#table1", data:{ items:[{name:'long name One',age:21},{name:'long name Two&a ...

Error Message: Unexpected Type Error with axios in Vue 3

Trying to implement axios in my Vue3 project for fetching APIs. Here is the code snippet from my component: export default { name: "Step2", data() { return { loading: true; }; }, mounted() { this.loading = false; }, ...

In the process of attempting to upload a .tsv file through the front end interface, I am encountering a challenge as the file remains stored on my server. What is the

I've got a function set up on my Express server that sends a file dependent on D3.JS. app.get('/dashboard', function(req, res) { var timestamp = utility.timestamp(); console.log('[' + timestamp + '] Request made to rend ...

Guide on converting JSON to CSV in React by utilizing the map function

When I convert JSON data to CSV by clicking a button, it currently stores the data in the CSV file separated by commas. However, I want each piece of data to be on its own line. How can I achieve this? For example: Minor,Minor What I Want: Each item on a ...

Error: The operation 'join' cannot be performed on an undefined value within Fast2sms

I am encountering issues while attempting to send SMS using fast2sms in Node.js. The error message reads as follows: TypeError: Cannot read property 'join' of undefined at Object.sendMessage (C:\Users\user\Desktop\node_module ...

The unexpected disappearance of data in a d3 v4 map leaves users puzzled

My current task involves reading data from a csv file and creating a map where the key is the state abbreviation and the value is the frequency of that state in the data. The code I have successfully creates the map, reads in the data, and when I use cons ...

error : failed to establish a connection to the MongoDB database

Ensure that the first parameter passed to mongoose.connect() or mongoose.createConnection() is a string. MongooseError: The uri parameter for openUri() must be a string, but it was "undefined". Double check that the initial parameter for mongoose.connect() ...

Attempting to transmit a ng-repeat object to a personalized filter function

Objective: The goal is to enable a user to input the name of a course into the search field and view a list of students who are enrolled in that course. Data Models: course (contains course name and code) student (holds a list of courses they are regist ...

Is it possible to leverage AngularJS for incorporating Dependency Injection into my Titanium Mobile Application?

Has this approach been attempted before and is it feasible? Are there alternative methods for incorporating DI into Titanium? In a Titanium Application, where should IOC be initialized and how? Is app.js the most suitable location for the composition root? ...

Discovering escape characters while iterating through a string in javascript

I have a situation where I must rearrange a string into an array for a unique user display. Whenever encountering an escape character (such as \n for a new line), it needs to be added as a separate item in the array. For example, if the string is: sa ...

Please refrain from populating my file with unnecessary data when using writeJSONString

Despite my efforts to write JSON data into a file, this simple piece of code is creating an empty file. import java.io.{File, FileWriter, IOException} import org.apache.http.client.ClientProtocolException import org.apache.http.client.fluent.Request impo ...

Fixing TypeError: Object #<IncomingMessage> has no method 'flash' in ExpressJS version 4.2

Currently, I am utilizing ExpressJS 4.2 and PassportJS for authenticating local users. Everything seems to be working smoothly except for when attempting to display a failureFlash message. Below is my configuration setup, thank you in advance! ==== Necess ...

Retrieve the value of a dynamically added or removed input field in JQuery using Javascript

Check out this informative article here I'm looking for a way to gather the values from all the text boxes and store them in an array within my JavaScript form. I attempted to enclose it in a form, but I'm struggling to retrieve the HTML ID beca ...

Parsing JSON data in Scala

Inbound JSON data consists of nested structures that do not directly correspond to predefined classes. Custom parsing is required for certain objects due to the case classes that have been created. { "uuid": "b547e13e-b32d-11ec-b909-0242 ...

Breaking apart a string that consists of boolean values

Presented below is a JavaScript function function cmd_parse( cmd ) { return cmd.split( /\s+/ ); } For instance, when calling the function like this words = cmd_parse("hello jay true"); The output would be words[0]="hello" words[1]="jay" wor ...

Executing operations on subdocuments in Mongoose without having to fetch the parent

Currently, when I need to delete a subdocument, I follow this process: Post.findById(post_id).exec(function(err, post) { post.comments.remove({'_id': comment_id}); post.save(function(err) { res.end("Success!"); }); }); This method doe ...

Remove a 2D array in MongoDB using C#

Hey there, I am facing an issue with my MongoDb database. I need to remove the index for "XD" from the "citations" field in my JSON data. How can I achieve this? { "_id" : ObjectId("604ca13de0059b65e4e67c01"), "username" : ...

Is there a way to retrieve the size of a three.js group element?

Obtaining the dimensions of a mesh (Three.Mesh) can be done using the following code: mymesh.geometry.computeBoundingBox() var bbox = mymesh.geometry.boundingBox; var bboxWidth = bbox.max.x - bbox.min.x; var bboxHeight = bbox.max.y - bbox.min.y; var bbo ...