我的问题是我想从服务器读取数据,因为它在一个角度应用程序中,而不重新加载页面。我有一个简单的烧瓶服务器,它在python中发送数据:
from threading import Timer
from flask import Flask
import time
import random
from datetime import datetime
from flask_cors import CORS, cross_origin
app = Flask(__name__)
cors = CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'
string = ''
humidity = 60
stress = 1
temperature = 20
def update_data(interval):
Timer(interval, update_data, [interval]).start()
global string
global humidity
global stress
global temperature
string = ''
string += f'{{"ID":"90A2DA10F2E4",'
string += f'"timestamp":"{datetime.now().isoformat()}",'
string += f'"temperature":{temperature},'
string += f'"humidity":{humidity},'
string += f'"stress":{stress}}}\n'
humidity = round( (humidity + (random.random()*2-1)), 2)
stress = round( (stress + (random.random()*0.2-0.1)), 2)
temperature = round( (temperature + (random.random()*0.2-0.1)), 2)
# update data every second
update_data(1)
@app.route("/")
@cross_origin()
def index():
return string
if __name__ == "__main__":
app.run(debug=True)
以角度形式创建订阅该流的组件:
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'prototype';
darkTheme = new FormControl(false);
list = [];
constructor(private streamService: TestDataService,
private http: HttpClient) { }
ngOnInit() {
this.privateServer();
}
privateServer() {
console.log("private server");
console.log(this.http.get('http://localhost:5000'));
this.http.get('http://localhost:5000').subscribe( data => {
console.log(data);
this.list.push(data);
})
}
onClick(){
console.log(this.list);
}
}
它将成为服务的一部分,但出于测试目的,我试图让它在组件内部工作。模板只包含一个调用onClick()的按钮。任何帮助,将不胜感激。
在Angular中,一旦Observable产生一个值,HttpClient
的请求方法就是为了complete
。因此,一旦触发了订阅回调,observable就会完成(不会再触发)。
要实现您的要求,您需要根据需要轮询数据或Web套接字。
对于Web套接字:
https://medium.com/factory-mind/angular-websocket-node-31f421c753ff
对于民意调查: