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

Submitting both $_POST[] data and $_FILES[] in a single AJAX request

Struggling with uploading images along with dates on my website. I am passing the date using $_POST and the image files in $_FILES. Here is the Javascript code snippet: (function post_image_content() { var input = document.getElementById("images"), ...

Utilizing SEO and incorporating special characters like !# in a website's URL

I came across an interesting concept about designing a website that utilizes AJAX to load each page section without compromising SEO. It involved incorporating !# in the URL, similar to the approach adopted by Twitter. However, I've been unable to loc ...

The database powered by Postgresql performs flawlessly when it comes to updating data with accurate code execution. However, there seems to be an

Imagine a zoo with a postgresql database. To enable web access to this database, I am using php and javascript. Most of the web pages are working fine, but I am currently working on a page where clients can add or remove animals from existing exhibits. T ...

Slide your finger upwards to shut down the mobile navbar in bootstrap

Hey there, I'm currently developing a website using Bootstrap framework v3.3.4. I have a mobile navbar that opens when I click a toggle button, but I would like it to slide up to close the navigation instead. Here is an image showing the issue Do y ...

MTG Life counter. Display fluctuations in count

I am currently working on a fun project creating an MTG (Magic The Gathering) life tracker, even though the code is quite messy. Despite its flaws, it still gets the job done. Click here to view the MTG life tracker https://i.stack.imgur.com/Su17J.png ...

What is the method for determining the numerical worth of the px containers?

https://i.stack.imgur.com/0K2TD.png Total width of the bar is set to 500px, with the red box at a width of 150px, the yellow box at 200px, and the green box at 50px. CSS Styles: .box { float:left; width:150px; box-shadow:3px 3p ...

Next.js components do not alter the attributes of the div element

I am encountering a problem with nextjs/reactjs. I have two tsx files: index.tsx and customAlert.tsx. The issue that I am facing is that the alert does not change color even though the CSS classes are being added to the alert HTML element. Tailwind is my c ...

Is there a way to manipulate a DOM element using a component?

import { FlagIcon, ChartIcon, ShareIcon, ConnectIcon, HearIcon, AnalyticsIcon, AddIcon, RemoveIcon, } from "../../icons/Icons"; import "./Sidebar.scss"; import ReactDOM from "react-dom"; const Sidebar = () =&g ...

Encountering unexpected errors with Typescript while trying to implement a simple @click event in Nuxt 3 projects

Encountering an error when utilizing @click in Nuxt3 with Typescript Issue: Type '($event: any) => void' is not compatible with type 'MouseEvent'.ts(2322) __VLS_types.ts(107, 56): The expected type is specified in the property ' ...

Removing all repetitions from an array in JavaScript

My collection of objects includes the following inputs: var jsonArray1 = [{id:'1',name:'John'},{id:'2',name:'Smith'},{id:'3',name:'Adam'},{id:'1',name:'John'}] There is a dupl ...

Error in Angular 2: The app.component.html file triggered an exception at line 1, character 108 due to excessive recursion

After successfully setting up the Angular 2 quickstart and connecting to an express server, I encountered a problem when switching from using the template property to component templateUrl. I have created a Plunker to showcase this issue: Plunker Demo imp ...

Comparing v-show(true/false) and replaceWith: Exploring the best practice between Vue and jQuery

Currently, I am in the process of learning vue.js and have a question regarding the best approach to implement the following scenario: The main query is whether it is acceptable in HTML to write <span></span> followed by a <textarea>< ...

Navigating the complexities of applying CSS exclusively to child grids within Kendo Angular may seem challenging at first

This image illustrates the grid layout I have created an angular UI using kendo that features a nested grid. I am trying to apply CSS specifically to the child grid without affecting the parent grid. However, no matter what CSS I write, it ends up being a ...

Challenges with Tab navigation in React and Ionic 5

I am facing a challenge with getting the tabs navigation to function correctly. Here is my current code: App.tsx: const App: React.FC = () => <IonApp> <IonReactRouter> <IonRouterOutlet id="main"> < ...

What are the steps to retrieve information from your personal server using Astro?

I have successfully set up a NodeJS server using Express and Astro for the frontend, with SSR configured through the Astro adapter for NodeJS. My current challenge is fetching data from the backend, and I am unsure of the correct approach to do so. Below ...

jQuery does not support the addition of new fields in HTML

Recently, I've been working on creating a lucky number generator. Initially, I developed it using C# and now I'm in the process of transitioning it to JavaScript and jQuery. You can view the latest version here. However, I've encountered an ...

Angular drag and drop functionality combined with interactive buttons for list management

Looking to create an Angular component for re-sorting objects by dragging from one list to another? I also need this component to include buttons for additional functionality. I've explored the various drag and drop components available on the Angula ...

Unable to attach the script to recently added DOM elements

After spending considerable time working on this, I'm still unable to figure it out. You can find the page I am referring to at: The "show more" button at the bottom triggers additional posts to be displayed on the page using the following script: ...

What is the correct way to promise-ify a request?

The enchanting power of Bluebird promises meets the chaotic nature of request, a function masquerading as an object with methods. In this straightforward scenario, I find myself with a request instance equipped with cookies via a cookie jar (bypassing req ...

Having trouble extracting a list of matches using a Regular Expression?

const stringWithDate: string = "4/7/20 This is a date!"; const reg: RegExp = new RegExp("^(\d{1,2}\/\d{1,2}\/\d{1,2})").compile(); const exist: boolean = reg.test(stringWithDate) const matches: RegExpExecArray | null = reg.exec(str ...