简体   繁体   English

Angular:Observable 服务无法从 api 获取数据

[英]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.我开始使用MatTableDataSource而不是DataSource并且从 api 获取数据时遇到问题。 When I use booking object as const array, it works fine.当我使用booking对象作为常量数组时,它工作正常。 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.但是当我想使用从api获取数据的服务时,不幸的是它不起作用,我的paginator显示0个元素。 Below I put my files:下面我把我的文件:

booking-table.component.ts预订表.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预订.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预订表.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.有人可以写出我的 get 方法有什么问题吗? Just to be clear, when I use DataSource it works fine, but when I use MatTableDataSource service get method doesn't work.需要明确的是,当我使用 DataSource 时它工作正常,但是当我使用 MatTableDataSource 服务时,get 方法不起作用。

A good practice is to use constructor only for injections, and to use hook methods, like ngOnInit for the rest.一个好的做法是仅将constructor用于注入,并使用钩子方法,例如ngOnInit用于其余部分。 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;
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM