Angular Material table 数据源未显示数据

Angular Material table data source not displaying data

我正在尝试使用 IEX 交易 api 创建 table 个股票报价。 但是,我在尝试将其连接到数据源时遇到问题。我能够使用 ngfor 并显示数据,但在尝试使用 table 时数据未显示。我不确定还能尝试什么。我在想这可能是我从 API 接收数据的方式。在服务 class 中,我尝试将其转换为数组,以便它可以与 table.

一起使用
@Component({
  selector: 'app-table',
  templateUrl: './table.component.html',
  styleUrls: ['./table.component.css']
})
export class TableComponent implements OnInit {
  displayedColumns: string[] = ['symbol'];
  quote:Quote[] = [];
  dataSource = new QuoteDataSource(this.stocksummary);

  constructor(private stocksummary:StocksummaryService) { }

  ngOnInit() {
  //  this.stocksummary.getStocks().subscribe(t => {this.quote = t});
  //  console.log(this.quote);

  }
}

export class QuoteDataSource extends DataSource<any> {
  constructor(private stocksummary:StocksummaryService)
  {
    super();
  }
  connect(): Observable<Quote[]>
  {
   var data = this.stocksummary.getStocks();
    console.log(data);
    return data;
  }



 disconnect(){}
}



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

@Injectable({
  providedIn: 'root'
})
export class StocksummaryService {
  quote:Quote[] = [];
  constructor(private http:HttpClient) { }
  getStocks():Observable<Quote[]> {
  this.http.get<Quote>("https://api.iextrading.com/1.0/stock/market/batch?symbols=AABA,AAPL,ABBV&types=quote")
  .subscribe(data => {
          for (var key in data) {
            if (data.hasOwnProperty(key)) {
             this.quote.push(data[key]["quote"]);
            }
          }
        });
        return observableOf(this.quote);
  }

}


export interface Quote {
    symbol?:                string;
    companyName?:           string;
    primaryExchange?:       PrimaryExchange;
    sector?:                string;
    calculationPrice?:      CalculationPrice;
    open?:                  number;
    openTime?:              number;
    close?:                 number;
    closeTime?:             number;
    high?:                  number;
    low?:                   number;
    latestPrice?:           number;
    latestSource?:          LatestSource;
    latestTime?:            LatestTime;
    latestUpdate?:          number;
    latestVolume?:          number;
    iexRealtimePrice?:      null;
    iexRealtimeSize?:       null;
    iexLastUpdated?:        null;
    delayedPrice?:          number;
    delayedPriceTime?:      number;
    extendedPrice?:         number;
    extendedChange?:        number;
    extendedChangePercent?: number;
    extendedPriceTime?:     number;
    previousClose?:         number;
    change?:                number;
    changePercent?:         number;
    iexMarketPercent?:      null;
    iexVolume?:             null;
    avgTotalVolume?:        number;
    iexBidPrice?:           null;
    iexBidSize?:            null;
    iexAskPrice?:           null;
    iexAskSize?:            null;
    marketCap?:             number;
    peRatio?:               number | null;
    week52High?:            number;
    week52Low?:             number;
    ytdChange?:             number;
}
export enum CalculationPrice {
    Close = "close",
}

export enum LatestSource {
    Close = "Close",
}

export enum LatestTime {
    February82019 = "February 8, 2019",
    January292019 = "January 29, 2019",
}

export enum PrimaryExchange {
    NASDAQGlobalMarket = "NASDAQ Global Market",
    NYSEArca = "NYSE Arca",
    NasdaqGlobalSelect = "Nasdaq Global Select",
    NewYorkStockExchange = "New York Stock Exchange",
}



<table mat-table [dataSource]="dataSource"
class="mat-elevation-z4" >

<ng-container matColumnDef="symbol">
    <th mat-header-cell *matHeaderCellDef> symbol </th>
    <td mat-cell *matCellDef="let item">
        {{item.symbol}} </td>
</ng-container>

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

您面临的问题是由于您在服务中订阅了 HTTP 请求,但随后 return 该订阅之外的数据(当请求很可能还没有被订阅时)尚未执行)。

我会这样写:

public getStocks(): Observable<Quote[]> {
  return this.http.get<Quote>("https://api.iextrading.com/1.0/stock/market/batch?symbols=AABA,AAPL,ABBV&types=quote")
    .pipe(map(data => {
      for (var key in data) {
        if (data.hasOwnProperty(key)) {
          this.quote.push(data[key]["quote"]);
        }
      }
      return this.quote;
    }));
}

这里我们发出请求,使用 pipemap 以您想要的方式转换您的数据,但不要实际订阅它,这将是 component/datasource。我们只是 return Observable 并且准备就绪。

同样在你的 ngOnInit 中你又犯了类似的错误,你订阅了 Observable 而没有 "waiting" 的响应你试图记录 return 值,应该是这样的:

ngOnInit() {
  this.stocksummary.getStocks().subscribe(t => {
    this.quote = t;
    console.log(this.quote);
  });    
}

Here is a working stackblitz that shows a working version of your code.