1

Im learning Angular and I'm creating a cryptocurrency exchange app. I created a service and an interface to get the data from an API. Now I can bind it to the DOM but I also want to use this data in my component.ts so I can write for example:

Bid2 = Bid * 2;

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

Thanks for your help. Here is my code:

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; 

}

Thanks for your help again!

2
  • Make a public property of the ComprarzecComponent, and call it Bid2. The template should be able to bind to it. The template should notice when you change the value. Commented Jun 21, 2017 at 22:25
  • In interpolation you can make math operations too: {{ Bid * 2 }} Commented Nov 2, 2017 at 13:54

2 Answers 2

2

Bid2 = Bid * 2;

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

The first thing worth noting is that for {{ Bid2 }} to work, Bid2 would need to be a property on ComprarzecComponent, but Bid is a property on MarketListObject, so it won't be as simple as just writing Bid2 = Bid * 2. You'll actually need to find the Bid2 for a particular MarketListObject, so it would be more like Bid2 = prices[index].Bid * 2.

For example.

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>

Going well though, as you're just starting out. People would generally trip over on the Http stuff first.

Sign up to request clarification or add additional context in comments.

Comments

1

Maybe my github could answer some of your questions.

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

An example of how I implement the order book service

Component

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

Models

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>

Using api can become confusing when the api has a CORS problem and that's why there is a Backend with NodeJs and Nodemon to avoid this problem. With Electron for example the problem is normally solved but for web app it's another story.

Angular without backend

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

If you choose a backend solution here is an example on nodeJS side

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

Another solution may be to use a proxy service as described in this article Access-Control-Allow-Origin: Dealing with CORS Errors in Angular

Another point to remember if you want to use something other than the public api of Bittrex. You will need the api keys generated by Bittrex, use post and HMAC-SHA512 (eg: Crypto-js).

Crypto-js : JavaScript library of crypto standards.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.