Creating, editing, and deleting data in Ng2 smart table is a seamless process that can greatly enhance

While working on my Angular 2 project, I utilized [ng2 smart table]. My goal was to send an API request using the http.post() method. However, upon clicking the button to confirm the data, I encountered the following error in the console:

ERROR TypeError: _co.addClient is not a function.

The code snippet in service.ts looks like this:

import { Injectable } from '@angular/core';
import { Clients } from './clients.model';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Observable} from 'rxjs';
@Injectable({
  providedIn: 'root'
})
export class ClientsService {

  url="http://localhost:21063/api/clints"
  clients:Clients[];
  client:Clients;

  constructor(private http:HttpClient) { }
getAllClients(): Observable<Clients[]>{
    return this.http.get<Clients[]>(this.url);

}
addClient(event){
this.http.post<Clients>(this.url,this.client)
.subscribe(
  res=>{
    console.log(res);

    event.confirm.resolve(event.Clients);
  },
  (err: HttpErrorResponse) => {
    if (err.error instanceof Error) {
      console.log("Client-side error occurred.");
    } else {
      console.log("Server-side error occurred.");
    }
  }
)
}

Here's my template:

        <div class="mainTbl">

            <ng2-smart-table 
            [settings]="settMain" 
            [source]="this.Service.clients"
            (createConfirm)="addClient($event)"
            (editConfirm)="onEditConfirm($event)"
            (deleteConfirm)="onDeleteConfirm($event)"
            ></ng2-smart-table>

        </div>

In addition, here's the content of my component .ts:

settMain = {
    noDataMessage: 'Sorry, no data available',

    actions: {
      columnTitle: 'Actions',
      position: 'right',
    },
    pager: {
      perPage: 5,
    },
    add: {
      addButtonContent: 'Add New ',
      createButtonContent: '',
      cancelButtonContent: '',
      confirmCreate: true,
    },
    edit: {
      editButtonContent: '',
      saveButtonContent: '',
      cancelButtonContent: '',
      confirmSave: true,

    },
    delete: {
      deleteButtonContent: '',
      confirmDelete: true,
    },

    columns: {
      id: {
        title: 'Client ID',
        width: '80px',
      },
      name: {
        title: 'Client Name',
        width: '160px'
      },
      phone: {
        title: 'Phone Number'
      },
      address: {
        title: 'Address'
      },
      account: {
        title: 'Balance'
      },
      notes: {
        title: 'Notes'
      }
    }
  };


  private myForm: FormGroup;

  constructor(private formBuilder: FormBuilder, private Service: ClientsService) { }

  ngOnInit() {

    this.Service.getAllClients().subscribe(data => this.Service.clients = data);
    this.Service.client={
      id:0,
      name:null,
      phone:null,
      address:null,
      type:null,
      account:0,
      nots:null,
      branchId:0,
    };

If anyone can help me identify my mistakes and suggest the best approach for handling create, edit, and delete operations, I would greatly appreciate it. Thank you in advance!

Answer №1

One reason for this is that the addClient method belongs to the service.ts, while the ng2-smart-table component is instantiated in another location. It is not recommended to directly call a service method from the template.

A better approach would be to create a method in your component.ts file that invokes the addClient method.

In the component.html template, you can link the editConfirm event to a separate method called onAddClient.

<div class="mainTbl">
  <ng2-smart-table 
    [settings]="settMain" 
    [source]="this.Service.clients"
    (createConfirm)="onAddClient($event)"
    (editConfirm)="onEditConfirm($event)"
    (deleteConfirm)="onDeleteConfirm($event)"
  ></ng2-smart-table>
</div>

In the component.ts file:

onAddClient(event) {
  this.Service.addClient(event).subscribe(
    (res) => {
      // handle success
    }, (error) => {
     // handle error
    });

}

Moreover, within the service.ts file, you will pass data from the component and return the response from an HTTP request using the HTTP Client.

addClient(data){
  console.log(data);
  return this.http.post<Clients>(this.url, data);
}

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

At times, Express.js may display an error message stating "Cannot GET /"

My objective is to have http://localhost:3000/app display myFile.html and http://localhost:3000/api return "It worked!". I currently have two files set up for this: App.js: const http = require('http'); const fs = require('fs&apo ...

What is the significance of utilizing app.set() and app.get() in applications?

Is there a way to simplify this code: app.set('port', (process.env.PORT || 3000)); const server = app.listen(app.get('port'), () => { console.log('Server|Port: ', app.get('port')); }); Here is an alternative ...

React application experiencing continuous SpeechRecognition API without stopping

I need assistance with integrating speech recognition into my web application using Web API's speech recognition feature. Below is the React code I am currently working with: import logo from './logo.svg'; import './App.css'; impor ...

How can PHP be used to decode JSON and transmit it to Javascript?

I am aiming to utilize the Twitter API in order to dynamically populate slides on a webpage with recent tweets without needing to refresh the entire page. Currently, my approach involves making an AJAX call every few seconds from a JavaScript function on ...

Tips for managing Material-ui's <Autocomplete/> component based on the option's id

When dealing with HTML select in React, it's common to use an id or key to keep track of the selected value: <select value={value} onChange={(event) => setValue(event.target.value)}> {options.map((option) => ( <option value={optio ...

Implementing a custom type within a generic function

Struggling with a particular problem, I am trying to figure out whether it is possible to pass a custom type or if only native TypeScript types (such as string and number) can be passed into a generic type implementation for an interface: type coordinates ...

Only one choice for discriminated unions in react props

Looking to create a typescript type for react component props, specifically a basic button that can accept either an icon prop or a text prop, but not both. My initial attempt with a discriminated union didn't quite produce the desired outcome: inter ...

Troubleshooting and Fixing AJAX Calls

When working with Asynchronous JavaScript, it is common to encounter issues where we are unsure of the posted request and received response. Is there a simple method for debugging AJAX requests? ...

Strange behavior in Angular's http response

When I make a call to my API and receive a JSON response, the code snippet below illustrates how I handle it: getAllLearn() { this.learnService.getAllLearn().subscribe(res =>{ // The console log shows that res.featured only has one index: ( ...

What is the method for generating a 2D array in JavaScript when the array's length is unknown?

I'm trying to create a 2D array that groups animals by their first letter of the alphabet. However, the output is not what I expected. I want each letter to have its own sub-array with corresponding animal names. Here's the code I tried: functio ...

Tips for retrieving the most recent UI updates after the container has been modified without the need to refresh the browser

Currently, I have developed a micro frontend application in Angular using module federation. This application is hosted in production with Docker containers. My main concern revolves around how to update the UI changes for the user without them needing to ...

Using webpack to load the css dependency of a requirejs module

Working with webpack and needing to incorporate libraries designed for requirejs has been smooth sailing so far. However, a bump in the road appeared when one of the libraries introduced a css dependency: define(["css!./stylesheet.css"], function(){ &bsol ...

Global Inertia Headers

How can I ensure that a custom header (Accept-Content-Language) is sent with every request, including Inertia manual visits? Below is the code snippet where I define and set the header: import axios from 'axios'; const lang = localStorage.getIt ...

Error encountered in TypeScript's Map class

When working with TypeScript, I keep encountering an error message that reads "cannot find name Map." var myMap = new Map(); var keyString = "a string", keyObj = {}, keyFunc = function () {}; // assigning values to keys myMap.set(keyString, "val ...

My goal is to store the received response in an array within an object

const data = [ { id: 1, user_name: 'john', phone_number: 5551234567 }, { id: 2, user_name: 'jane', phone_number: 5559876543 }, { id: 3, user_name: 'doe', ...

Executing a function after the completion of another

Here is my function: function functionName($results) { //do some stuff disableSave() } When this function runs, I want to call the enableSave() function. How can I achieve this? I attempted to pass the function as a callback but I am unsure wher ...

Is the row removed from the table after successful deletion?

I am struggling to remove the deleted row from the table. The code I tried is not working as expected. Here is the scenario: When a user clicks on the delete link/button, it sends a delete request and removes the data from the Database. After successful de ...

Can I apply a universal babel configuration across all of my personal projects?

It becomes tedious to duplicate the same configuration file for each new project I start. ...

Monaco utilized for Angular web-based code editing platform

We recently created an online code editor in our project using the Monaco editor. Our next goal is to integrate an Angular editor into this platform. To achieve this, we require NPM support to install dependencies directly from the editor. If anyone has ...

TypeScript purity - "The variable exports is not defined"

I encountered an issue with my simple client-server TypeScript application where every import statement in my client.ts file triggers a ReferenceError: exports is not defined error in the browser after loading the HTML. Here is the project structure: root ...