damman96
damman96

Reputation: 13

Angular: Observable service doesn't get data from api

I started to use MatTableDataSource instead of DataSource and I got a problem to get data from api. When I use booking object as const array, it works fine. But when I want to use the service, which will get data from api, unfortunately it doesn't work, and my paginator shows 0 elements. Below I put my files:

booking-table.component.ts

import { Component, OnInit, ViewChild } from '@angular/core';
import {MatPaginator, MatSort, MatTableDataSource} from '@angular/material';
import {BookingService} from "../../service/booking.service";

export interface BookingI {
  id: number;
  bookingDate: string;
  bookingTime: string;
  date: string;
  time: string;
  boardId: number;
  employeeId: number;
  personalData: string;
  phoneNumber: number;
  description: string;
}

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

export class BookingTableComponent implements OnInit {
  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;
  dataSource: MatTableDataSource<BookingI>;

  displayedColumns = ['id', 'personalData', 'phoneNumber'];

  booking: BookingI[] = [];

  constructor(private bookingService: BookingService) {

    this.bookingService.getAllBookings()
      .subscribe(value => this.booking = value);

    this.dataSource = new MatTableDataSource(this.booking);
    console.log(this.dataSource);
  }

  ngOnInit() {
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;
  }
}

booking.service.ts

import { Injectable } from '@angular/core';
import {HttpClient, HttpHeaders} from "@angular/common/http";
import {Observable} from "rxjs";
import {Booking} from "../model/booking";
import {catchError} from "rxjs/operators";

@Injectable({
  providedIn: 'root'
})
export class BookingService {

  private httpOptions = {
    headers: new HttpHeaders({'Content-Type': 'application/json'})
  };

  constructor(private http: HttpClient) {
  }

  getAllBookings(): Observable<Booking[]> {
    const url = 'http://localhost:8080/bookings';
    return this.http.get<Booking[]>(url)
      .pipe(catchError(this.handleError));
  }

  private handleError(error: any): Promise<any> {
    console.error('Error', error); // for demo purposes only
    return Promise.reject(error.message || error);
  }
}

booking-table.component.html

<div class="mat-elevation-z8">
  <table mat-table [dataSource]="dataSource" matSort>

    <ng-container matColumnDef="id">
      <th mat-header-cell *matHeaderCellDef mat-sort-header>Id</th>
      <td mat-cell *matCellDef="let booking">{{booking.id}}</td>
    </ng-container>

    <ng-container matColumnDef="personalData">
      <th mat-header-cell *matHeaderCellDef mat-sort-header>Dane klienta</th>
      <td mat-cell *matCellDef="let booking">{{booking.personalData}}</td>
    </ng-container>

    <ng-container matColumnDef="phoneNumber">
      <th mat-header-cell *matHeaderCellDef mat-sort-header>Nr telefonu</th>
      <td mat-cell *matCellDef="let booking">{{booking.phoneNumber}}</td>
    </ng-container>

    <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
    <tr mat-row *matRowDef="let booking; columns: displayedColumns;">
    </tr>
  </table>

  <mat-paginator [pageSizeOptions]="[5, 10, 25, 100]"></mat-paginator>
</div>

Does someone can write what's wrong with my get method. Just to be clear, when I use DataSource it works fine, but when I use MatTableDataSource service get method doesn't work.

Upvotes: 1

Views: 649

Answers (1)

veben
veben

Reputation: 22322

A good practice is to use constructor only for injections, and to use hook methods, like ngOnInit for the rest. Try to replace your code by something like that:

constructor(private bookingService: BookingService) {
}

ngOnInit() {

    this.bookingService.getAllBookings().subscribe(value => {
        console.log(value);
        this.dataSource = value;
        this.dataSource.paginator = this.paginator;
        this.dataSource.sort = this.sort;
    });
}

Upvotes: 1

Related Questions