PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, March 18, 2022

[FIXED] i generate ng material data table using schematic. i tried replacing their dummy data with data from api, but couldn't get it done

 March 18, 2022     angular, angular-material, php, phpmyadmin     No comments   

Issue

this is the interface Tickets[]

export interface Tickets {
    name: string;
    id: number;
  }

this is the service i created that should return data fetched from API.. but here i hard coded the data (please someone should help me with right function that will return the data from api in getData() function)

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Tickets } from './ticket.model'

@Injectable({
  providedIn: 'root'
})
export class OpenTicketsService {
  private _url:string = 'assets/data.json';

  constructor(private http: HttpClient) { }

  dataRequest():Observable<Tickets[]>{
    return this.http.get<Tickets[]>(this._url);

  }

  getData(){
    //to be replace with the code that will subscribe to `dataRequest()` and return the data
    return [
      {id: 1, name: 'Hydrogen'},
      {id: 2, name: 'Helium'},
      {id: 3, name: 'Lithium'},
      {id: 4, name: 'Beryllium'},
      {id: 5, name: 'Boron'},
      {id: 6, name: 'Carbon'},
      {id: 7, name: 'Nitrogen'},
      {id: 8, name: 'Oxygen'},
      {id: 9, name: 'Fluorine'},
      {id: 10, name: 'Neon'},
    ];
  }

this is datasource.ts file generated along with angular material data-table

import { DataSource } from '@angular/cdk/collections';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { map } from 'rxjs/operators';
import { Observable, of as observableOf, merge } from 'rxjs';
import { OpenTicketsService } from './open-tickets.service';
import { Tickets } from './ticket.model';


export class TicketsTableDataSource extends DataSource<Tickets> {

//this is the function that will return the data from OpenTicketsService and assign it to "data"

 data: Tickets[] = this.ticketService.getData();
  paginator: MatPaginator;
  sort: MatSort;

  constructor(private ticketService:OpenTicketsService) {
    super();
  }

  connect(): Observable<Tickets[]> {
    const dataMutations = [
      observableOf(this.data),
      this.paginator.page,
      this.sort.sortChange
    ];

    return merge(...dataMutations).pipe(map(() => {
      return this.getPagedData(this.getSortedData([...this.data]));
    }));
  }

  disconnect() {}

  private getPagedData(data: Tickets[]) {
    const startIndex = this.paginator.pageIndex * this.paginator.pageSize;
    return data.splice(startIndex, this.paginator.pageSize);
  }

  private getSortedData(data: Tickets[]) {
    if (!this.sort.active || this.sort.direction === '') {
      return data;
    }

    return data.sort((a, b) => {
      const isAsc = this.sort.direction === 'asc';
      switch (this.sort.active) {
        case 'name': return compare(a.name, b.name, isAsc);
        case 'id': return compare(+a.id, +b.id, isAsc);
        default: return 0;
      }
    });
  }
}

function compare(a: string | number, b: string | number, isAsc: boolean) {
  return (a < b ? -1 : 1) * (isAsc ? 1 : -1);
}

component.ts file that will display the data on the component.html

import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { MatTable } from '@angular/material/table';
import { TicketsTableDataSource } from './tickets-table-datasource';
import { Tickets } from './ticket.model';
import { OpenTicketsService } from './open-tickets.service';

@Component({
  selector: 'app-tickets-table',
  templateUrl: './tickets-table.component.html',
  styleUrls: ['./tickets-table.component.scss']
})
export class TicketsTableComponent implements AfterViewInit, OnInit {
  constructor(private ticketService:OpenTicketsService) { }
  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;
  @ViewChild(MatTable) table: MatTable<Tickets>;
  dataSource: TicketsTableDataSource;

  /** Columns displayed in the table. Columns IDs can be added, removed, or reordered. */
  displayedColumns = ['id', 'name'];

  ngOnInit() {
    this.dataSource = new TicketsTableDataSource(this.ticketService);
  }

  ngAfterViewInit() {
    this.dataSource.sort = this.sort;
    this.dataSource.paginator = this.paginator;
    this.table.dataSource = this.dataSource;
  }
}

Solution

the data source can not be a "service"!!

Futhermore, you needn't use ngAfterView and a View Child to give all properties to your table, see the example in the docs

I suppose you want to write some like

ngAfterViewInit() {
    this.tickerService.dataRequest().subscribe(res=>{
       this.dataSource = new TicketsTableDataSource(res);
       this.dataSource.sort = this.sort;
       this.dataSource.paginator = this.paginator;
       this.table.dataSource = this.dataSource;
    })
  }

See that it's all under subcribe function

NOTE: If you use {static:true} you can asign the paginator in ngOnInit



Answered By - Eliseo
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing