
[英]How to handle socket.io acknowledgement from service.ts to component.ts on emit success Angular 8
[英]How to return a response through a socket.io channel of the success or error of an Angular8 service
我正在做Web和移动应用程序之间的聊天应用程序。 我的情况如下。 我实现了套接字服务器,并且在Angular应用程序的OnInit函数中,听到了来自外部应用程序的消息。 消息到达时运行服务以将该消息插入数据库。 我需要知道如何返回将消息插入到外部应用程序的服务所给出的响应,因为在将消息插入数据库的函数中可能存在多种变体和错误类型。
app.component.ts(这里是)
ngOnInit(){
this.id_usuario_logueado=1;
this.socket.on('message',(msg) =>{
this.mandar_mensaje(msg);
});
}
mandar_mensaje(datos){
let chat:ChatService;
if(this.id_usuario_logueado!=datos.id_user_from){
this._chatService.sendMessage(datos.id_user_from,datos.id_user_to,datos.mensaje).subscribe(
response=>{
if (this.compInstances[datos.id_user_from] && this.compInstances[datos.id_user_from].instance.isActive) {
this._chatService.getMessages(1,datos.id_user_from).subscribe(
response=>{
if(response.mensajes){
this.compInstances[datos.id_user_from].instance.mensajes=response.mensajes;
}
},
error=>{
console.log(error);
}
);
}else {
console.log('Window not active');
}
},
error=>{
console.log(error);
}
);
}
}
chat.service.ts(我在这里调用API REST)
sendMessage(id_user_from,id_user_to,contenido):Observable<any>{
var datos = {id_user_from:id_user_from,id_user_to:id_user_to,contenido:contenido};
return this._http.post(this.url+'send_message',datos);
}
API REST(这是一个同时运行两个应用程序的所有服务都位于的API)
function send_message($request) {
$parametros=$request->getParsedBody();
$id_user_from=$parametros['id_user_from'];
$id_user_to=$parametros['id_user_to'];
$contenido=$parametros['contenido'];
if ($id_user_from == "" || $id_user_to == "" ) {
echo '{ "response": "000" , "message" : "Fields required."}';
exit;
}
$sql = "INSERT INTO Mensaje (id_user_from, id_user_to, contenido,fecha) VALUES ($id_user_from, $id_user_to, '".$contenido."',NOW())";
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->execute();
echo '{ "response": "101" , "message" : "Sucess!!"}';
} catch(PDOException $e) {
echo '{ "response": "000" , "message" : "Error in query."}';
}
}
服务器节点
io.on('connection', function(socket){
socket.on('message', function(datos){
console.log(datos.mensaje);
io.emit('message', datos);
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.