Angular:可观察的服务无法从api获取数据

时间:2018-12-27 19:03:28

标签: angular typescript angular-material observable angular7

我开始使用MatTableDataSource而不是DataSource,但从api获取数据时遇到问题。当我将booking对象用作const数组时,它可以正常工作。但是,当我想使用将从api获取数据的服务时,不幸的是它不起作用,我的paginator显示了0个元素。我在下面放文件:

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>

有人可以写出我的get方法有什么问题吗?需要明确的是,当我使用DataSource时,它工作正常,但是当我使用MatTableDataSource服务时,get方法不起作用。

1 个答案:

答案 0 :(得分:1)

一个好的做法是仅将constructor用于注入,而将钩子方法(如ngOnInit用于其余的注入)。尝试用类似这样的代码替换您的代码:

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;
    });
}