gpt4 book ai didi

node.js - Angular 2 实时刷新应用

转载 作者:太空宇宙 更新时间:2023-11-03 23:25:15 24 4
gpt4 key购买 nike

我是 Angular 和 Nodejs 的新手,我正在尝试构建一个平均堆栈加密货币交换应用程序。我创建了一个 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());
}
}

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>

最佳答案

如果您希望每 5 或 10 秒定期轮询一次,那么使用 Web Worker 没有任何优势。一般来说,网络 worker 对于聊天应用程序等双向通信很有用。

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

关于node.js - Angular 2 实时刷新应用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45156206/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com