0

我正在尝试使用 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>
4

1 回答 1

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

是一个工作堆栈闪电战,它显示了您的代码的工作版本。

于 2019-02-15T07:33:50.260 回答