首页 > 解决方案 > 如何将Javascript添加到角度html?

问题描述

我正在 Angular 应用程序中创建一个实时聊天,我有这两个类,我正在使用 Socket.io

服务器.js

const http = require('http');
const app = require('./backend/app');
const port = process.env.PORT || 3000;


app.set('port', port);
const server = http.createServer(app);



const io = require('socket.io')(server, {
  cors: {
    origins: ['http://localhost:4200']
  }
});



const sockets = [];

io.on('connection', (socket) => {
    sockets.push(socket);
    console.log(`New connection ${socket.id}`);
     //io.emit('user.add', socket.id);


    socket.on('chat', function(msg){

      for(var i = 0; i < sockets.length; i++){
        sockets[i].send(msg)
        console.log(msg);



    }
    io.sockets.emit('chat', msg);
  });




    socket.on('disconnect', () => {

      io.emit('user.remove', socket.id);

        for(var i = 0; i < sockets.length; i++){
            if(sockets[i].id === socket.id){
                sockets.splice(i, 1); //deleta um elemento do array (posicao, numero de elementos a ser excluido)
            }
        }
        console.log(`o id: ${socket.id} saiu ` + 'agora restam ' + sockets.length + ' online')
    })
})

server.listen(port);

...................................................

HTML

<head>
    <style>
      * { margin: 0; padding: 0; box-sizing: border-box; }
      body { font: 13px Helvetica, Arial; }
      form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
      form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
      form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
      #messages { list-style-type: none; margin: 0; padding: 0; }
      #messages li { padding: 5px 10px; }
      #messages li:nth-child(odd) { background: rgb(12, 255, 12); }
    </style>


    <title>Painel de Controle</title>
  </head>
  <body>
    <style>
      body {
        background-image: url(assets/img/backgroundloginfade.jpg);
        background-attachment: fixed;
        background-size: 100%;
        background-repeat: no-repeat;
        height: 1500px;
      }
    </style>
       <button
       class="btn-navgation"
       type="button"
       value="Voltar"
       onClick="history.go(-1)"
     >
       <img src="assets/img/back_icon.png" width="75px" alt="" />
     </button>

     <div class="chat_window">
      <div class="top_menu">
          <div class="buttons">
              <div class="button close"></div>
              <div class="button minimize"></div>
              <div class="button maximize"></div>
          </div>
          <div class="title">Chat</div>
      </div>


      <ul id ="messages" class="messages">

        <div id="output" *ngFor="let data of output">
          <p>{{data.message}}</p>
      </div>

      </ul>




      <div class="bottom_wrapper clearfix">




          <div class="message_input_wrapper">

              <input placeholder="Digite sua mensagem!" class="message_input" type="text" id="message" autocomplete="off" [(ngModel)]="message" (keypress)="messageTyping()"/>
          </div>


          <button class="send_message" type="button" id="send" (click)="sendMessage()">Enviar</button>

      </div>
      <div id="message"></div>
  </div>

    </body>

...................................................

而且我需要在我的 HTML 中添加一个脚本(下面的代码),但它不能直接将标签脚本 src 添加到 HTML 中......那么我如何将下面的脚本添加到我的 html 中(所有 3 个脚本)?

<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>

<script>
  $(function () {
    var socket = io();
    $('form').submit(function(){
      socket.emit('chat', $('#m').val());
      $('#m').val('');
      return false;
    });
    socket.on('chat', function(msg){
      $('#messages').append($('<li>').text(msg));
    });
  });
</script>

标签: javascripthtmlangular

解决方案


Angular 默认索引页面通常位于src/app/index.html。您可能希望在 head 中添加前两个脚本标签,在结束 body 标签之前添加最后一个。

像这样:

<html>
  <head>
  // ...All your other stuff here
  <script src="/socket.io/socket.io.js"></script>
  <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
  </head>
  <body>
    <app-root></app-root>
    <script>
      $(function () {
        var socket = io();
        $('form').submit(function(){
        socket.emit('chat', $('#m').val());
        $('#m').val('');
        return false;
      });
      socket.on('chat', function(msg){
        $('#messages').append($('<li>').text(msg));
      });
     });
   </script>
  </body>
</html>

    

这可能足以进行测试,但请记住,出于多种原因,这不是好的做法。一旦你测试过它,你应该将 socket.io 添加为项目依赖项(https://www.npmjs.com/package/socket.iohttps://www.npmjs.com/package/ngx-socket-io ) 并控制组件控制器内的 DOM。


推荐阅读