问题描述
我正在简单地显示Gemini比特币网络套接字中的数据。我可以订阅websocket,并在我的订阅函数中处理传入的消息。这一切都按预期工作。当我处理新消息时,dataFromMessages会更改值。
使dataFromMessages成为可观察的下一步是什么?
我知道它是否是可观察的,那么我可以在HTML中使用“ | async”。或者,我可以订阅Observable。但是我不知道如何使它成为可观察的。使用or()函数?
output.component.ts
import { Component,OnInit } from '@angular/core';
import { UserWebsocketService } from '../services/user-websocket.service';
export class OutputComponent implements OnInit{
dataFromMessages;
constructor(private websocket: UserWebsocketService){}
ngOnInit(): void {
this.websocket.connect('wss://api.gemini.com/v1/marketdata/btcusd')
.subscribe(message => this.process_message(message));
}
process_message(message){
// *** do processing here with incoming message object***
this.dataFromMessages = processed_data;
}
}
output.component.html
<table>
<thead>
<tr> <th>Bid</th> <th>Ask</th> </tr>
</thead>
<tbody>
<tr *ngFor="let item of dataFromMessages">
<td>{{ item.bid }}</td>
<td>{{ item.ask }}</td>
</tr>
</tbody>
</table>
解决方法
将dataFromMessages
初始化为可观察的;
dataFromMessages$: Observable<any>;
ngOnInit(): void {
this.dataFromMessages$ = this.websocket.connect('wss://api.gemini.com/v1/marketdata/btcusd')
.pipe(tap(message) => this.process_message(message));
}
然后在process_message
方法中返回已处理的消息。
process_message(message){
// *** do processing here with incoming message object***
return processed_data;
}
然后在模板中使用异步管道来订阅和读取数据。
<tr *ngFor="let item of dataFromMessages$ | async">
<td>{{ item.bid }}</td>
<td>{{ item.ask }}</td>
</tr>
,
您应该将dataFromMessages声明为所需类型的可观察对象。 然后在ngOnInit()中,在管道内使用rxjs map()运算符进行处理并将其返回。在这里,您可以使用“正常”消息,并且在管道完成后,将使用在管道内部使用的运算符对它进行观察。
然后在HTML中使用异步管道
EINTEGRITY
<tr *ngFor="let item of dataFromMessages$ | async">
<td>{{ item.bid }}</td>
<td>{{ item.ask }}</td>
</tr>