[英]Attribution of a value with socket.io and Angular
我正在尝试使用以下代码通过socket.io获取数据:
server.js:
io.sockets.on('connection', function (socket) {
console.log('Un client est connecté !');
retrieveDB((res) =>{
socket.emit('dataSend', res);
});
});
filesearch.component.ts:
import * as io from 'socket.io-client';
options = []
socket = io.connect('http://localhost:4200');
ngOnInit(){
this.socket.on('dataSend', function(message) {
this.options = message;
alert(message);
});
if(this.myControl.value !='') {
this.init = 1;
this.filteredOptions = this.myControl.valueChanges
.pipe(
startWith(''),
map(val => this.filter(val))
);
} else {
this.init = 0;
}
}
filter(val: string): string[] {
if(this.init){
return this.options.filter(option =>
option.toLowerCase().includes(val.toLowerCase()));
} else {
return []
}
}
ngOnInit()
应该使用ngOnInit()
检索数据,第二部分初始化一个自动socket.on()
( https://material.angular.io/components/autocomplete/overview ),但是我始终具有options
nul的值。 我知道这段代码是错误的,因为socket.on
可以异步工作,但是我找不到如何纠正它。
我试图通过这样做来更改代码:
ngOnInit(){
this.socket.on('dataSend', function(message) {
this.options = message;
alert(message);
});
}
onClick(){
if(this.myControl.value !='') {
this.init = 1;
this.filteredOptions = this.myControl.valueChanges
.pipe(
startWith(''),
map(val => this.filter(val))
);
} else {
this.init = 0;
}
当我单击搜索栏时,运行onClick()
。 但是我仍然得到相同的结果。 所以我开始认为问题出在代码的其他地方。 alert(this.options)
返回正确的值,仅此而已。
我也尝试创建一个“ Display Button
以在单击它时显示options
的值,但我仍然没有正确的答案。
我还尝试用ngOnInit()
的回调创建一个异步函数:
ngOnInit(){
this.socket.on('dataSend', function(message) {
this.initialise(message, this.autocompletion());
});
}
initialise(message, callback){
this.options = message;
alert(message);
callback();
}
autocompletion(){
if(this.myControl.value !='') {
this.init = 1;
this.filteredOptions = this.myControl.valueChanges
.pipe(
startWith(''),
map(val => this.filter(val))
);
} else {
this.init = 0;
}
但这不起作用。
感谢您的帮助或至少阅读了此消息。
编辑:我尝试了另一种方法
我有一个dictionnarymanagerService :
export class DictionnarymanagerService implements OnInit{
data: any = ['test2'];
socket = io.connect('http://localhost:4200');
constructor() {}
ngOnInit() {
this.socket.on('dataSend', function(message) {
this.options = message;
alert(message);
});
}
而且我只有在fileSearchComponent中 :
选项= []
ngOnInit(){
this.options = this.dictionnaryManager.data;
if(this.myControl.value !='') {
this.init = 1;
this.filteredOptions = this.myControl.valueChanges
.pipe(
startWith(''),
map(val => this.filter(val))
);
} else {
this.init = 0;
}
}
但是因为socket.on
是异步的,所以我没有正确的值( options
取值为'test2
。如何在socket.on()
结束后发送data
值
您不使用箭头功能,因此this
是指您在socket.on
提供的功能。 箭头功能不能捕获this
。
您可以查看此问题以获取更多信息: 箭头函数与函数声明/表达式:它们是否等效/可互换?
由于箭头功能无法捕获this
,因此以下代码应能正常工作,因此this
仍引用组件类的实例:
ngOnInit() {
this.socket.on('dataSend', message => this.options = message);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.