Angular 2 TypeScript using SignalR

后端 未结 3 1115
面向向阳花
面向向阳花 2021-02-05 21:34

I\'m trying to set up an Angular 2 application to use Microsoft\'s SignalR. I\'ve been following this tutorial, which although it\'s good I don\'t like the fact that jQuery and

相关标签:
3条回答
  • you can try

    npm install ng2-signalr --save
    

    you can read the setup instructions here,
    There is also a link to a working demo.

    0 讨论(0)
  • 2021-02-05 22:07

    Here's a startup code you can use.

    C#

    //create an interface that contains definition of client side methods
    public interface IClient
    {
        void messageReceived(string msg);
    }
    
    //create your Hub class that contains implementation of client methods
    public class ChatHub : Hub<IClient>
    {
        public void sendMessage(string msg)
        {
            //log the incoming message here to confirm that its received
    
            //send back same message with DateTime
            Clients.All.messageReceived("Message received at: " + DateTime.Now.ToString());
        }
    }
    

    HTML

    Add reference to script files of jQuery and signalR.

    <script src="path/to/jquery.min.js"></script>
    <script src="path/to/jquery.signalR.min.js"></script>
    
    <!--this is the default path where SignalR generates its JS files so you don't need to change it.-->
    <script src="~/signalr/hubs"></script>
    

    JS

    You need to install TypeScript definition file for SignalR and jQuery. If you're using TypeScript 2, you don't need to add reference to index.d.ts file while using it. Just install the typings using following commands.

    npm install --save @types/jquery
    npm install --save @types/signalr
    

    With all the setup done, you can write a simple TypeScript class to handle the logic for sending and receiving messages.

    export class MessageService {
        //signalR connection reference
        private connection: SignalR;
        
        //signalR proxy reference
        private proxy: SignalR.Hub.Proxy;
    
    
        constructor() {
            //initialize connection
            this.connection = $.connection;
            
            //to create proxy give your hub class name as parameter. IMPORTANT: notice that I followed camel casing in giving class name
            this.proxy = $.connection.hub.createHubProxy('chatHub');
    
            //define a callback method for proxy
            this.proxy.on('messageReceived', (latestMsg) => this.onMessageReceived(latestMsg));
    
            this.connection.hub.start();
        }
        
        private onMessageReceived(latestMsg: string) {
            console.log('New message received: ' + latestMsg);
        }
    
        //method for sending message
        broadcastMessage(msg: string) {
            //invoke method by its name using proxy 
            this.proxy.invoke('sendMessage', msg);
        }
    }
    

    I'm using the above code, obviously modified to my needs, and it works fine.


    Update 1: This is a pretty old answer and things have changed a lot since then. Install jQuery and SignalR using npm and then load them using angular.json file, like this:

    1- Install npm install jquery signalr

    2- Load in angular.json -> projects -> your-app -> architect -> build -> options

    scripts: [
      "./node_modules/jquery/dist/jquery.min.js", 
      "./node_modules/signalr/jquery.signalR.min.js"
    ]
    

    Thanks and credits to Robert's answer for update.

    0 讨论(0)
  • 2021-02-05 22:24

    @Syed Ali Taqi's answer is basically OK but not perfect(even not working if you miss configuring ts compiler). Here's my steps for newest Angular(version 8 as of my writing):

    1. Install jquery and signalr run time libs: npm install jquery signalr
    2. Tell Angular to load the libs at run time as if they were in the <script></script> tag by configuring angular.json :

      projects:
        <your-app>:
          architect:
            build:
              options:
                ...
                scripts: [
                  "./node_modules/jquery/dist/jquery.min.js",
                  "./node_modules/signalr/jquery.signalR.min.js"
                ]
            ...
            test:
              options:
                ...
                scripts: [
                  "./node_modules/jquery/dist/jquery.min.js",
                  "./node_modules/signalr/jquery.signalR.min.js"
                ]
      
    3. Install types for jquery and signalr so that the ts compiler can recognize them: npm install @types/jquery @types/signalr --save-dev

    4. Tell the ts compiler to load the types by default by editing the types section of tsconfig.app.json and tsconfig.spec.json:
      compilerOptions:
        types: [..., "jquery", "signalr"]
      

    OK, all done! Happy SignalR coding!

    let conn = $.hubConnection("<base-path>");
    let proxy = conn.createHubProxy("<some-hub>");
    ...
    

    Note: never try to import ... from jquery explicitly in your code, as said by https://angular.io/guide/using-libraries#using-runtime-global-libraries-inside-your-app

    For more info on angular.json configuration, see https://angular.io/guide/workspace-config

    0 讨论(0)
提交回复
热议问题