1
我是Angular和Nodejs的新手,我試圖構建一個平均堆棧加密貨幣交換應用程序。 我創建了一個nodejs後端從API獲取當前匯率並將其顯示在html中。此外,我創建了貨幣兌換組件並且工作正常。我需要每5或10秒更新html和貨幣兌換組件。Angular 2實時刷新應用程序
我的第一個問題是,如果它更好地在後端或前端做到這一點,第二個問題是我如何做到這一點。
這裏是我的代碼:
api.js
const express = require('express');
const router = express.Router();
// declare axios for making http requests
const axios = require('axios');
const coinTicker = require('coin-ticker');
/* GET api listing. */
router.get('/', (req, res, next) => {
res.send('api works');
});
router.get('/posts', function(req, res, next) {
coinTicker('bitfinex', 'BTC_USD')
.then(posts => {
res.status(200).json(posts.bid);
})
.catch(error => {
res.status(500).send(error);
});
});
module.exports = router;
prices.component
import { Component, OnInit } from '@angular/core';
import { PricesService } from '../prices.service';
import { Observable } from 'rxjs';
@Component({
selector: 'app-posts',
})
export class PricesComponent implements OnInit {
// instantiate posts to an empty array
prices: any;
targetAmount = 1;
baseAmount = this.prices;
update(baseAmount) {
this.targetAmount = parseFloat(baseAmount)/this.prices;
}
constructor(private pricesService: PricesService) { }
ngOnInit() {
// Retrieve posts from the API
this.pricesService.getPrices().subscribe(prices => {
this.prices = prices;
console.log(prices);
});
}
}
Prices.service
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class PricesService {
constructor(private http: Http) { }
// Get all posts from the API
getPrices() {
return this.http.get('/api/posts')
.map(res => res.json());
}
}
HTML
<div class="form-group">
<label for="street">Tipo de Cambio</label>
<input type="number" class="form-control" id="street" [value]="prices" disabled> CLP = 1 BTC
</div>
謝謝!有效! –