question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Got no success populating Angular 4 datatable.net with json data using httpClient 2 and interface.

See original GitHub issue

Before you write your question, please take some extra time to write a good title that is short yet descriptive.

What versions you are using?

  • node version: v8.4.0
  • npm version: v5.4.0
  • angular version: v4.3.1
  • jquery version: ^1.12.4
  • datatables version: 1.10.12
  • datatables.net: 1.10.16
  • angular-datatables version: ^4.4.1
  • angular-cli version: 1.5.0

What’s the problem?

Got no success populating Angular 4 datatable.net with json data using httpClient 2 and interface. You may note that the json data is already printed on the console but not populating the datatable itself.

import { Component, OnInit, ElementRef, ViewChild, AfterViewInit } from '@angular/core';
import { DateAdapter } from '@angular/material';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

import {FormControl} from '@angular/forms';
import { DataTableDirective } from 'angular-datatables';
import { Subject } from 'rxjs/Rx';
import { Router } from '@angular/router';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import {Observable} from "rxjs/Observable";
import * as _ from 'lodash';

declare const require: any;
declare const $: any;


declare interface User {
    text?: string; // required, must be 5-8 characters
    email?: string; // required, must be valid email format
    password?: string; // required, value must be equal to confirm password.
    confirmPassword?: string; // required, value must be equal to password.
    number?: number; // required, value must be equal to password.
    url?: string;
    idSource?: string;
    idDestination?: string;
}

declare interface Usuario {
  nome: string;
  email: string;
  perfil: string;
  status: string;
}

@Component({
  selector: 'app-gestao-usuarios',
  templateUrl: './gestao-usuarios.component.html',
  styleUrls: ['./gestao-usuarios.component.css']
})


export class GestaoUsuariosComponent implements OnInit, AfterViewInit {
  title = 'app';
  public user: User;
  public typeValidation: User;
  constructor (private router: Router, private http: HttpClient){}

  @ViewChild(DataTableDirective)
  dtElement: DataTableDirective;
  // Must be declared as "any", not as "DataTables.Settings"
  dtOptions: DataTables.Settings = {};
  dtTrigger: Subject<any> = new Subject();

  selectedValue: string;
  chosenPerfil: string;
  chosenStatus: string;

  selectTheme = 'primary';
  perfil = [
    {value: 'administrador', viewValue: 'Administrador'},
    {value: 'fornecedor', viewValue: 'Fornecedor'},
    {value: 'solicitante', viewValue: 'Solicitante'},
  ];

  status = [
    {value: 'naoregistrado', viewValue: 'Não registrado'},
    {value: 'registrado', viewValue: 'Registrado'},
    {value: 'cadastro', viewValue: 'Cadastro'},
    {value: 'cadastrofinalizado', viewValue: 'Cadastro finalizado'},
  ];

  ngOnInit(): void {

    let req = this.http.get<Usuario>('https://api.myjson.com/bins/yg64b')
    .subscribe (
      res => {
        console.log(res);
      }, (err: HttpErrorResponse) => {
      if (err.error instanceof Error) {
        console.log("Ocorrência Error Frontend")
      } else {
        console.log("Ocorrência Error Backend")
      }
    }
 )

   this.user = {
     text:'',
     email: '',
     password: '',
     confirmPassword: ''
 };
   this.typeValidation = {

       text: '',
       email: '',
       idSource: '',
       idDestination: '',
       url: ''
   };
 }

 save(model: User, isValid: boolean) {
   // call API to save customer
   //console.log(model, isValid);
   this.clickPost(model);
 }

 onSubmit(value: any): void {
     console.log(value);
 }

 clickPost(user: User){

   let body = {nome: user.text,
     email: user.email,
     password: user.password,
     perfil: this.chosenPerfil,
     status: this.chosenStatus
   };

   let req = this.http.post('https://jsonplaceholder.typicode.com/posts', body)
   .subscribe (
     res => {
       console.log (res);
     }, (err: HttpErrorResponse) => {
     if (err.error instanceof Error) {
       console.log("Ocorrência Error Frontend")
     } else {
       console.log("Ocorrência Error Backend")
     }
   }
  )
 }

 myFunc(val: any) {
     console.log('value is changed to ' + val);
 }

 ngAfterViewInit(): void {
   this.dtTrigger.next();
 }

 rerender(): void {
    this.dtElement.dtInstance.then((dtInstance: DataTables.Api) => {
      // Destroy the table first
      dtInstance.destroy();
      // Call the dtTrigger to rerender again
      this.dtTrigger.next();
    });
  }

    goToGestao(){
        this.router.navigate(['gestao-usuario']);
    }

    goToCadastro(){
        this.router.navigate(['cadastro-usuario']);
    }

}


Issue Analytics

  • State:closed
  • Created 6 years ago
  • Comments:17 (4 by maintainers)

github_iconTop GitHub Comments

1reaction
l-lincommented, Nov 25, 2017

Using the Angular’s documentation, here an example on plunker.

As for your second question, check this answer.

1reaction
l-lincommented, Nov 25, 2017

You need to call dtTrigger.next() after you populate your variable usuarios. In your code, I don’t see where it’s initialized… 🤔

In my example, you will see that I call dtTrigger.next() after I affected the server response to my variable persons.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Datatables.Net - not populating from JSON data
The issue Im facing is in the variable JSON, I can see that I have returned a JSON response, and it is valid...
Read more >
Integrate Data table with Angular 8 Application With JSON ...
Integrate Data table with Angular 8 Application With JSON backend. WebSite | YouTube. DataTables is a plug-in for the JQuery JavaScript library.
Read more >
48 answers on StackOverflow to the most popular Angular ...
by Shlomi Levi 48 answers on StackOverflow to the most popular Angular questions I gathered the most common questions and answers from ......
Read more >
JavaScript Data Grid Configuration - DevExtreme - DevExpress
Do not specify the fields array because the DataGrid automatically populates it to sync filter builder fields with grid columns. NOTE. In Angular...
Read more >
DataTable Won't Populate JSON Object to Table
Hello, so I was having issues with my DataTable, and now I fixed the main issue I was facing which was getting the...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found