代码之家  ›  专栏  ›  技术社区  ›  claudiomatiasrg

Angular 2实时刷新应用程序

  •  0
  • claudiomatiasrg  · 技术社区  · 9 年前

    我创建了一个nodejs后端,从API获取当前汇率,并将其显示在html中。此外,我还创建了货币兑换组件及其运行良好。我需要每隔5秒或10秒更新html和货币兑换组件。

    我的第一个问题是在后端还是在前端更好,第二个问题是我如何做到。

    这是我的代码:

    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;
    

    价格.组件

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

    价格.服务

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

    <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>
    
    1 回复  |  直到 9 年前
        1
  •  2
  •   CozyAzure    9 年前

    如果你想每隔5秒或10秒定期投票,使用网络工作者没有任何优势。一般来说,网络工作者将有助于双向通信,如聊天应用程序。

    我认为在您的情况下,可以使用客户端正常轮询。使用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]);
    
    推荐文章