Teresa Alves
Teresa Alves

Reputation: 523

Error: Cannot send data if the connection is not in the 'Connected' State. Why my signalR connection isn't working?

I'm trying to implement SignalR on my project. Here is the code of my Index.cshtml where I start the connection and then I get data from URL. Everytime I run my code I get the error !"Error: Cannot send data if the connection is not in the 'Connected' State" and it doesn't show the map like it used to before I installed the SignalR.

var connection = new signalR.HubConnectionBuilder().withUrl("/myHub").build();

connection.on("ReDesignMap", function () {
//script que retorna todas as ignições presentes na base de dados 
  //$(document).ready(function ()    {

$.get( "/api/IgnicoesAPI", function( data ) {
  $.each(data, function (i, item) {  
                //janela de informação de cada marcador 
    var estado = "em avaliação"
    var infowindow = '<div id="content" style="hight:700px; width:500px">' +
                    '<div id="siteNotice">' +
                    '</div>' +
                    '<div id="bodyContent">' +
                    '<p><b>Avaliação da Ocorrência:</b></p>' +
                    // iterar todas as ocorrencias para tirar delas as imagens
                    //$.each(item.ListaOcorrencias, function (f, foto) {
                    //    '<img src="https://wpde.com/resources/media/83f69602-210f-4ad1-bad0-bd5cf19470c7-large16x9_MARIONWOODSFIRE2.jpeg?1553519933510https://wpde.com/resources/media/83f69602-210f-4ad1-bad0-bd5cf19470c7-large16x9_MARIONWOODSFIRE2.jpeg?1553519933510" onclick="openModal();currentSlide(1)" class="hover-shadow" style="width:70px; height:60px" hspace="4">' +

                    //        });


                            '<img src="https://upload.wikimedia.org/wikipedia/commons/b/b6/Controlled_burn_to_restore_mountain_longleaf_pine_in_northwest_Georgia_-_170317-FS-Chattahoochee-Oconee-SB-062_%2833575304935%29.jpg" onclick="openModal();currentSlide(2)" class="hover-shadow" style="width:70px; height:60px" hspace="4">' +
                        '<img src="https://b50ym1n8ryw31pmkr4671ui1c64-wpengine.netdna-ssl.com/wp-content/blogs.dir/11/files/2016/09/wildfire_px-1024x500.png" onclick="openModal();currentSlide(3)" class="hover-shadow" style="width:70px; height:60px" hspace="4">' +        
                    //
                    '<p></p>' +
                    '<div class="button-holder">' +
                    '<a href="#slider-image-1" class="slider-change"></a>' +
                    '<a href="#slider-image-2" class="slider-change"></a>' +
                    '<a href="#slider-image-3" class="slider-change"></a>' +
                    '</div>' +
                    '</div> ' + 
                    '<p id="estadoP"> Estado: '+ estado +'</p>'+
                    '<button id="aceite" onclick="aceite()" style="background-color:#4CAF50;border: none;color: white;padding: 5px 12px;text-align: center;display: inline-block;font-size: 16px; box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2), 0 6px 20px 0 rgba(0,0,0,0.19); margin:5px;">Aceitar</button>' +
                    '<button id="recusado" onclick="recusado()" style="background-color:#f44336;border: none;color: white;padding: 5px 12px;text-align: center;display: inline-block;font-size: 16px; box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2), 0 6px 20px 0 rgba(0,0,0,0.19);margin:5px;" >Recusar</button>' +
                    '<button id="concluido" onclick="concluido()" style="background-color:#008CBA;border: none;color: white;padding: 5px 12px;text-align: center;display: inline-block;font-size: 16px; box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2), 0 6px 20px 0 rgba(0,0,0,0.19);margin:5px;" > Concluído</button>' +
                    '</div>';

                //definição do icon para o marcador
   var ignicao = L.icon({
                    iconUrl: 'https://cdn3.iconfinder.com/data/icons/basicolor-signs-warnings/24/186_fire-512.png',
                    iconSize: [35, 35], // size of the icon
                });
                //colocar um marcador no mapa de acordo com a latitude e longitude fornecidas 
                var marker = new L.marker([item.latitude, item.longitude], { icon: ignicao })
                    .bindPopup(infowindow)
                    .on('click', onClick)
                    .addTo(map);
                //adiciona marador ao mapa
      $('#json map').append(marker);


            }); // fim do 'for each'
   });


 });

connection.invoke("ReDesignMap").catch(function (err) {
 return console.error(err.toString());
});

Upvotes: 3

Views: 18282

Answers (2)

Jalal Malekpour
Jalal Malekpour

Reputation: 37

you must delay with method setTimeout like under

setTimeout(function () {
       connection.invoke("ReDesignMap");
}, 2000);

Upvotes: -1

Christoph L&#252;tjen
Christoph L&#252;tjen

Reputation: 5804

You have to connect to signalr server first.

var connection = new signalR.HubConnectionBuilder().withUrl("/myHub").build();
await connection.start();

connection.invoke("ReDesignMap").catch(function (err) {
  return console.error(err.toString());
});

// or if you don't use async/await style
var connection = new signalR.HubConnectionBuilder().withUrl("/myHub").build();
connection.start().then(() => {
  connection.invoke("ReDesignMap").catch(function (err) {
    return console.error(err.toString());
  });
}

See https://learn.microsoft.com/en-us/aspnet/core/signalr/javascript-client?view=aspnetcore-3.1 for a complete example.

Upvotes: 2

Related Questions