Angular 2 TypeScript using SignalR

后端 未结 3 1116
面向向阳花
面向向阳花 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条回答
  •  滥情空心
    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 tag by configuring angular.json :

      projects:
        :
          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("");
    let proxy = conn.createHubProxy("");
    ...
    

    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

提交回复
热议问题