Angular 4、typescript将接口属性赋值给变量

Angular 4, typescript Assign interface property to variable

我正在学习 Angular 并且我正在创建一个加密货币交换应用程序。我创建了一个服务和一个接口来从 API 中获取数据。现在我可以将它绑定到 DOM 但我也想在我的 component.ts 中使用这些数据所以我可以写例如:

出价2 = 出价* 2;

然后将该变量绑定到 DOM,如下所示:{{ Bid2 }}

感谢您的帮助。这是我的代码:

Component.ts

import { Component, OnInit } from '@angular/core';
import { Http, Response, Headers } from '@angular/http';
import { BittrexService } from '../../bittrex/bittrex.service';
import {Observable} from "rxjs";
import { MarketListObject } from '../datosmoneda';
import { MarketPrices } from '../datosmoneda';

@Component({
  selector: 'app-comprarzec',
  templateUrl: './comprarzec.component.html',
  styleUrls: ['./comprarzec.component.scss']
})
export class ComprarzecComponent implements OnInit {

  private prices = [];


  constructor(private bittrexService: BittrexService) {
    this.bittrexService = bittrexService;
  }

ngOnInit(){
  this.bittrexService.getPrices()
  .subscribe(
    data => this.prices = data.result
  );
}
 }

Service.ts

import { Injectable } from '@angular/core';
import { Http, Headers, Response } from '@angular/http';
import 'rxjs/add/operator/toPromise';
import {Observable} from "rxjs";
import 'rxjs/Rx';
import 'rxjs/add/operator/catch';
import { MarketViewModel } from '../comprarmonedas/datosmoneda'


@Injectable()
export class BittrexService {

  constructor(private http: Http, private marketModel : MarketViewModel) { }

  public getPrices() :Observable<MarketViewModel> {
    return this.http.get('https://bittrex.com/api/v1.1/public/getmarketsummary?market=btc-zec')
    .map((response: Response) => response.json());
  }

}

interface.ts (datosmoneda.ts);

export class MarketViewModel {
  public success : boolean;
  public message : string;
  public result : MarketListObject[];
}

export class MarketListObject {
    public MarketName : string;
    public High : number;
    public Low : number;
    public Volume : number;
    public Last : number;
    public BaseVolume : number;
    public TimeStamp : number;
    public Bid : number;
    public Ask : number;
    public OpenBuyOrders : number;
    public OpenSellOrders : number;
    public PrevDay : number;
    public Created : number; 

}

再次感谢您的帮助!

Bid2 = Bid * 2;

and then bind that variable to the DOM like this: {{ Bid2 }}

首先要注意的是 {{ Bid2 }} 要工作,Bid2 需要是 ComprarzecComponent 上的 属性,但 BidMarketListObject上的属性,所以不会像写Bid2 = Bid * 2那么简单。您实际上需要找到特定 MarketListObject 的 Bid2,因此它更像是 Bid2 = prices[index].Bid * 2.

例如

component.ts

@Component({
    selector: 'app-comprarzec',
    templateUrl: './comprarzec.component.html',
    styleUrls: [ './comprarzec.component.scss' ]
})
export class ComprarzecComponent implements OnInit {
    private prices: MarketListObject[] = [];

    constructor(private bittrexService: BittrexService) {
    }

    bid2(price: MarketListObject): number {
        return price.Bid * 2;
    }

    ngOnInit() {
        this.bittrexService.getPrices().subscribe(data => {
            this.prices = data.result;
        });
    }
}

comprarzec.component.html

<ul>
    <li *ngFor="let price of prices">
        {{price.Bid}}
        {{bid2(price)}}
    </li>
</ul>

进展顺利,因为您才刚刚起步。人们通常会首先被 Http 的东西绊倒。

也许我的 github 可以回答您的一些问题。

Ng-CC-Exchange : CryptoCurrencies Exchanges Module for Angular(2+)

一个我如何实现订单簿服务的例子

组件

getBittrexOrderBook(market) {
if (market !== '') {
  this._bittrexService.getOrderBook(market).subscribe(
    response => {
      if (response.success && response.result) {
        this._tempCurrencyBuy = response.result;
      } else {
        this.handleError(response.message);
      }
    },
    error => this.handleError(error)
  );
}}

型号

export interface BittrexOrderBook{
    success: boolean;
    message: string;
    result: BittrexOrder[];
}

export interface BittrexOrder{
    Quantity: number;
    Rate: number;
}

Html

<div class="bittrex-currencies-container">
<div class="bittrex-currencies-sub-container">
    <div class="bittrex-currencies-title">
        <h3 class="bittrex-currencies-title"><strong> Bittrex order book</strong></h3>
    </div>
    <form #form="ngForm" name="form" (ngSubmit)="submit()">
        <input type="text" class="search-input" placeholder="search engine" [(ngModel)]="filter" name="ngModel">
        <button type="submit" class="btn">submit</button>
    </form>
    <div class="scroll-bar">
        <div class="row" *ngIf="_tempCurrencyBuy.length">
            <div class="col-md-6">
                <label class="label label-default" for="bittrex-info-content">Buy orders</label>
                <div class="bittrex-currencies" *ngFor="let currency of _tempCurrencyBuy">
                    <div class="bittrex-info" *ngIf="currency.Quantity">
                        <label class="label label-info" for="bittrex-info-content">Quantity</label>
                        <span id="bittrex-info-content">{{currency.Quantity}}</span>
                    </div>
                    <div class="bittrex-info" *ngIf="currency.Rate">
                        <label class="label label-info" for="bittrex-info-content">Rate</label>
                        <span id="bittrex-info-content">{{currency.Rate}}</span>
                    </div>
                    <br>
                </div>
            </div>
            <div class="col-md-6">
                <label class="label label-default" for="bittrex-info-content">Sell orders</label>
                <div class="bittrex-currencies" *ngFor="let currency of _tempCurrencySell">
                    <div class="bittrex-info" *ngIf="currency.Quantity">
                        <label class="label label-info" for="bittrex-info-content">Quantity</label>
                        <span id="bittrex-info-content">{{currency.Quantity}}</span>
                    </div>
                    <div class="bittrex-info" *ngIf="currency.Rate">
                        <label class="label label-info" for="bittrex-info-content">Rate</label>
                        <span id="bittrex-info-content">{{currency.Rate}}</span>
                    </div>
                    <br>
                </div>
            </div>
        </div>
    </div>
</div>

当 api 出现 CORS 问题时,使用 api 可能会变得混乱,这就是为什么有一个带有 NodeJs 和 Nodemon 的后端来避免这个问题。 以 Electron 为例,问题通常已经解决,但对于网络应用程序,则是另一回事了。

Angular 无后端

getOrderBook(market, type = 'both', depth = 50) {
if (market) {
    return this._http.get(this._BASE_URL + `/getorderbook?market=${market}&type=${type}&depth${depth}`)
        .map(response => response.json() as BittrexOrderBook)
        .timeout(this._timeOut);
    }}

如果您选择后端解决方案,这里是 nodeJS 端的示例

_api.get(_BITTREX_BASEURL + '/getorderbook', (request, response) => {
console.time("getorderbook");
const market = request.query.market;
const type = request.query.type;
const depth = request.query.depth;
const url = `https://bittrex.com/api/v1.1/public/getorderbook?market=${market}&type=${type}&depth${depth}`;
httpGet(url, response);
console.timeEnd("getorderbook");});


function httpGet(url, response) {
    _client.get(url, (data, resp) => {
        response.json(data);
    });
}

另一种解决方案可能是使用本文所述的代理服务 Access-Control-Allow-Origin: Dealing with CORS Errors in Angular

如果您想使用 Bittrex public api 以外的其他东西,请记住另一点。您将需要 Bittrex 生成的 api 密钥,使用 post 和 HMAC-SHA512(例如:Crypto-js)。

Crypto-js : JavaScript library of crypto standards.