我是angular的新手。我想从套接字服务器获取连续的动态数据。服务器端很好,但是我无法从套接字服务器接收数据。
答案 0 :(得分:1)
这将有效,请尝试以下操作:
1。首先,您必须以类似的角度创建组件:
socketComponent.ts
import { SocketDataService } from 'socketDataService';
import { Subscription } from 'rxjs';
@Component({
selector: 'app-socket',
templateUrl: './app-socket.component.html',
styleUrls: ['./app-socket.component.css'],
})
export class SocketComponent implements OnInit {
sub: Subscription;
constructor(private socketDataService: SocketDataService) {}
ngOnInit() {
this.getSocketData();
}
getSocketData(): void {
this.sub = this.socketDataService.getSocketData()
.subscribe(data => {
this.socketData = data
})
}
}
2。您必须创建以下服务:
socketService.ts
import { Observable } from 'rxjs/Observable';
@Injectable()
export class SocketDataService {
private socket;
constructor(private http: Http) {
this.socket = io('http://localhost:3000')
}
observer
getSocketData(): Observable<any> {
this.socket.on('socket-data', (res) => {
this.observer.next(res);
});
return this.getSocketDataObservable();
}
getSocketDataObservable(): Observable<any> {
return new Observable(observer => {
this.observer = observer;
});
}
}
答案 1 :(得分:0)
更简单的方法
import * as io from 'socket.io-client';
ngOnInit() {
this.socket = io('hostname');
this.socket.on('socket_event', (data) => {
console.log(data);
}.bind(this));
}