使用 SignalR 的 Angular 2 TypeScript

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41378582/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:07:51  来源:igfitidea点击:

Angular 2 TypeScript using SignalR

jqueryangulartypescriptwebpacksignalr

提问by Daniel Grima

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 SignalR are loaded into the application via script tags in the index.html file and also the fact that both libraries do not use their respective Type Definitions.

我正在尝试设置一个 Angular 2 应用程序以使用 Microsoft 的 SignalR。我一直在关注本教程,虽然它很好,但我不喜欢通过 index.html 文件中的脚本标签将 jQuery 和 SignalR 加载到应用程序中的事实,以及两个库不使用它们各自的类型的事实定义。

So with that in mind I've been trying to include jQuery and SignalR in my application using node modules and the respective Type Definitions. I've searched the correct type definition files to use through Microsoft's TypeSearch.

因此,考虑到这一点,我一直在尝试使用节点模块和相应的类型定义在我的应用程序中包含 jQuery 和 SignalR。我已经通过 Microsoft 的TypeSearch搜索了要使用的正确类型定义文件。

I'm only including jQuery in my application because of SignalR's dependency on jQuery.

由于 SignalR 对 jQuery 的依赖,我只在我的应用程序中包含 jQuery。

jQuery

jQuery

I first started with installing the jQuery module in my application which I've had to add in the Webpack configuration as well. After this was set up I'm being faced with a "conflict" issue because of Protractor. This is described on Aurelia JS Rocks' website. Although it suggests uninstalling the protractor typings I tried our another solution for now described in this answer. I don't know if this is the best solution.

我首先在我的应用程序中安装 jQuery 模块,我也必须将其添加到 Webpack 配置中。设置完成后,由于量角器,我面临“冲突”问题。这在Aurelia JS Rocks 的网站上有描述。尽管它建议卸载量角器类型,但我尝试了本答案中现在描述的另一种解决方案。我不知道这是否是最好的解决方案。

SignalR

信号R

With regards to SignalR I'm a bit stuck - so far it seems there's no "official" node module provided for SignalR. I'm not sure whether I should include Microsoft's SignalR Javascript Library by downloading the file and including it in my application.

关于 SignalR,我有点卡住了 - 到目前为止,似乎没有为 SignalR 提供“官方”节点模块。我不确定是否应该通过下载文件并将其包含在我的应用程序中来包含 Microsoft 的 SignalR Javascript 库。

The issue is that I have installed the Type Definitions for SignalR. But now I'm not sure how to go about actually using SignalR since when I type $or jQueryI'm not being suggested .connectionsfor example - which makes sense as this is not part of the jQuery library.

问题是我已经安装了 SignalR 的类型定义。但是现在我不确定如何实际使用 SignalR,因为当我输入$jQuery没有被建议时.connections,例如 - 这是有道理的,因为这不是 jQuery 库的一部分。

I'm sure that I might be misunderstanding something with regards to getting it "set up". What's the best way to go about using SignalR in an Angular2 TypeScript application?

我敢肯定,我可能对“设置”它有一些误解。在 Angular2 TypeScript 应用程序中使用 SignalR 的最佳方法是什么?

回答by Syed Ali Taqi

Here's a startup code you can use.

这是您可以使用的启动代码。

C#

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

HTML

Add reference to scriptfiles of jQueryand signalR.

添加引用script的文件jQuerysignalR

<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

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.tsfile while using it. Just install the typings using following commands.

您需要为 SignalR 和 jQuery安装TypeScript 定义文件。如果您正在使用TypeScript 2,则无需index.d.ts在使用时添加对文件的引用。只需使用以下命令安装类型。

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

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

完成所有设置后,您可以编写一个简单的TypeScript class来处理发送和接收消息的逻辑。

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.

我正在使用上面的代码,显然已根据我的需要进行了修改,并且运行良好。

回答by hannes neukermans

you can try

你可以试试

npm install ng2-signalr --save

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

你可以在这里阅读设置说明,
还有一个工作演示的链接。

回答by Robert

@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):

@Syed Ali Taqi 的回答基本上可以,但并不完美(如果您错过了配置 ts 编译器,甚至无法正常工作)。这是我最新 Angular 的步骤(我写作时的版本 8):

  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 defaultby editing the typessection of tsconfig.app.json and tsconfig.spec.json:
    compilerOptions:
      types: [..., "jquery", "signalr"]
    
  1. 安装 jquery 和 signalr 运行时库: npm install jquery signalr
  2. <script></script>通过配置 angular.json告诉 Angular 在运行时加载库,就像它们在标签中一样:

    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. 为 jquery 和 signalr 安装类型,以便 ts 编译器可以识别它们: npm install @types/jquery @types/signalr --save-dev

  4. 通过编辑tsconfig.app.json 和 tsconfig.spec.json 部分,告诉 ts 编译器默认加载类型types
    compilerOptions:
      types: [..., "jquery", "signalr"]
    

OK, all done! Happy SignalR coding!

好了,大功告成!快乐 SignalR 编码!

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

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

注意:永远不要尝试在你的代码中明确地import ...from jquery,正如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

有关 angular.json 配置的更多信息,请参阅https://angular.io/guide/workspace-config