2017-07-18 7 views
1

私はAngular、Nodejs、Imで新しく平均スタック暗号化交換アプリケーションを構築しようとしています。 私はnodejsバックエンドを作成して、現在の為替レートをAPIから取得し、それをhtmlに表示しました。また、私は外貨両替コンポーネントとそれを正常に動作させました。 htmlと通貨交換のコンポーネントを5秒または10秒ごとに更新する必要があります。角2リアルタイムのリフレッシュアプ​​リ

私の最初の質問は、バックエンドまたはフロントエンドでそれを行う方が良い場合で、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> 

答えて

2

5秒または10秒ごとに定期的にポーリングを行う場合は、Webワーカーを使用する利点はありません。一般に、ウェブワーカーは、チャットアプリケーションのような双方向通信に役立ちます。

あなたのケースでは、クライアントサイドの通常のポーリングを使用することができます。 rxjsを使用してクライアント側のポーリングを実装するのは非常に簡単です。

return Observable.interval(5000) // call once 5 per second 
    .startWith(0) 
    .switchMap(() => { 
     return this.http.get('/api/posts') 
      .map(res => res.json()) 
    }) 
    .map(value => value[0]); 
+0

ありがとうございます!出来た! –

関連する問題