角度服务:
createObservableSocket(url: string, id: number): Observable<any> {
let a = new Observable<string>(
observer => {
this.ws.onmessage = (event) => {
observer.next(event.data);
console.log('event data:', event.data); // event data: [{"productId":1,"bid":3616.8217831199527}]
}
this.ws.onerror = (event) => observer.error(event);
this.ws.onopen = (event) => this.sendMessage({productId: id});
this.ws.onclose = (event) => observer.complete();
}
);
console.log('a:', a); // [Observable object]
let b = a.map(message => {
JSON.parse(message);
});
console.log('b:', b); // [Observable object]
return b;
}
sendMessage(message: any) {
console.log('client ws service msg:', JSON.stringify(message)); //client ws service msg: {"productId":1}
this.ws.send(JSON.stringify(message));
}
角度分量
watchProduct() {
this.isWatched = !this.isWatched;
this.wsService.createObservableSocket('ws://localhost:8085',
this.product.id)
.subscribe(
products => {
console.log('component received:', products); //component received: undefined
let product = products.find( p => p.productId === this.product.id);
this.currentBid = product.bid;
}
);
}
Angular version: 4.2.4
Browser:
- [ ] Chrome (desktop) version 60.0.3112.101
For Tooling issues:
- Node version: v8.1.0
- Platform: Windows 10
答案 0 :(得分:0)
您需要return
数据:
所以改变这个:
a.map(message => {
JSON.parse(message);
});
致:
a.map(message => {
return JSON.parse(message);
});
// OR
a.map(message => JSON.parse(message));