角材料表数据源不显示数据

时间:2019-02-10 19:53:19

标签: angular api angular-material angular-material-table

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

@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>

1 个答案:

答案 0 :(得分:0)

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

我会这样写:

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来以您想要的方式转换您的数据,但实际上并没有订阅它,这将是组件/数据源的工作。我们只需退还Observable,就可以了。

在您的ngOnInit中,您又犯了一个类似的错误,您正在订阅Observable,而没有“等待”您试图记录返回值的响应,它应该像这个:

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

Here是有效的堆叠闪电战,显示了您的有效版本   代码。