SignalR,带有Angular 10和ASP.NET

sy5wg1nm  于 2023-02-10  发布在  .NET
关注(0)|答案(4)|浏览(228)

我正试图在一个asp.net(不是核心)和angular(目前有10个)应用程序中实现signalr。startupidocs正在使用owin。
我能找到的每一个文档或示例都是针对ASP.NET核心的,或者没有使用Angular,所以有人能给我指出一个好的方向吗?
我能找到的最接近这个组合的是这个指南:https://www.c-sharpcorner.com/article/asp-net-signalr-angular2-and-typescript-real-time-clock/,但是我一直收到"无法读取未定义的属性" hubConnection ""错误,可能是因为我不明白"$"在SignalRService类中的作用,因为我开始使用Angular 7和更高版本。
任何帮助都将不胜感激。

xggvc2p6

xggvc2p61#

U可以使用此链接中的示例SignalR using Angular 10
步骤:
1.安装所需的信号库
npm i@微软/信号@最新--保存
1.导入所需的类
从"@microsoft/signalr "导入{集线器连接、集线器连接生成器、日志级别};
1.连接到集线器

this._hubConnection = new HubConnectionBuilder()
  .withUrl('http://localhost:52864/chathub')
  .build();

1.侦听集线器上的方法

this._hubConnection.on('MessageReceived', (message) => {
  console.log(message);
});

1.启动连接

this._hubConnection.start()
  .then(() => console.log('connection started'))
  .catch((err) => console.log('error while establishing signalr connection: ' + err));

虚拟示例的外观:

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { HubConnection, HubConnectionBuilder, LogLevel } from '@microsoft/signalr';

@Component({
  selector: 'app-messaging',
  templateUrl: './messaging.component.html',
  styleUrls: ['./messaging.component.scss']
})
export class MessagingComponent implements OnInit {
  private _hubConnection: HubConnection;

  constructor(private _httpClient: HttpClient) { }

  ngOnInit(): void {
    this.connect();
  }

  public onSendButtonClick(): void {
    this._hubConnection.send('SendMessage', 'test message').then(r => { });
  }

  private connect(): void {
    this._hubConnection = new HubConnectionBuilder()
      .withUrl('http://localhost:52864/chathub')
      .build();

    this._hubConnection.on('MessageReceived', (message) => {
      console.log(message);
    });

    this._hubConnection.start()
      .then(() => console.log('connection started'))
      .catch((err) => console.log('error while establishing signalr connection: ' + err));
  }
}

注:无需安装"signalr-protocol-msgpack"

irtuqstp

irtuqstp2#

旧的(非核心的)SignalR javascript客户端依赖于jQuery,所以在你的Angular 应用中添加对SignalR的支持的最好方法是
1.将jquery和signalr npm包添加到项目中
npm安装jquery信号--保存
1.添加@types/jquery和@types/signalr npm包,以便为这两个包提供类型支持。
npm安装@类型/jquery @类型/信号r--保存设备
1.编辑angular.json文件projects/[projectname]/architect/build/scripts节点,以包含jquery和signalr脚本(完整文件请参见下面的示例)
“脚本”:[./node_modules/jquery/dist/jquery.min.js”,./node_modules/signalr/jquery.signalR.js”]
1.编辑tsconfig.app.json文件并将“jquery”、“signalr”添加到“compilerOptions”/“types”列表中。(完整文件请参见下面的示例)
angular.json应该是这样的(这里的项目名称是signalr demo)

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "signalrdemo": {
      "projectType": "application",
      "schematics": {},
      "root": "",
      "sourceRoot": "src",
      "prefix": "app",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/signalrdemo",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.app.json",
            "aot": true,
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "src/styles.css"
            ],
            "scripts": [
              "./node_modules/jquery/dist/jquery.min.js",
              "./node_modules/signalr/jquery.signalR.js"
            ]
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true,
              "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "2mb",
                  "maximumError": "5mb"
                },
                {
                  "type": "anyComponentStyle",
                  "maximumWarning": "6kb",
                  "maximumError": "10kb"
                }
              ]
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "signalrdemo:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "signalrdemo:build:production"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "signalrdemo:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.spec.json",
            "karmaConfig": "karma.conf.js",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "src/styles.css"
            ],
            "scripts": []
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "tsconfig.app.json",
              "tsconfig.spec.json",
              "e2e/tsconfig.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        },
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "e2e/protractor.conf.js",
            "devServerTarget": "signalrdemo:serve"
          },
          "configurations": {
            "production": {
              "devServerTarget": "signalrdemo:serve:production"
            }
          }
        }
      }
    }},
  "defaultProject": "signalrdemo"
}

下面是tsconfig.app.json的外观:

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "./out-tsc/app",
    "types": ["jquery","signalr"]
  },
  "files": [
    "src/main.ts",
    "src/polyfills.ts"
  ],
  "include": [
    "src/**/*.d.ts"
  ]
}
cmssoen2

cmssoen23#

我犯了一个简单的错误,没有在Service的声明之上声明jQuery符号:

declare var $: any;

例如:

declare var $: any;  
@Injectable()  
export class SignalRService {  ...

这个关于如何使用jQuery和Angular的链接告诉了我:
https://blog.bitsrc.io/how-to-use-jquery-with-angular-when-you-absolutely-have-to-42c8b6a37ff9

km0tfn4u

km0tfn4u4#

Signalr依赖于jquery,因此首先需要安装

npm install signalr
npm install jquery

以及它们的类型

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

将脚本添加到angular-cli.json

"architect": {
    "build": {
      ...
      "options": {
        "scripts": [
          "node_modules/jquery/dist/jquery.min.js",
          "node_modules/signalr/jquery.signalR.min.js"
        ]
    ...

创建信号服务.ts文件:

import { Injectable } from '@angular/core';

declare var $: any;

@Injectable({
  providedIn: 'root'
})
export class SignalrService {

  private connection: any;
  private proxy: any;

  constructor() { }

  public initializeSignalRConnection(): void {
    this.connection = $.hubConnection(`${your_server_baseUrl}/signalr_map`, { useDefaultPath: false });
// Please note that by default '/signalr' URL will be used to connect to your SignalR service. Providing 'useDefaultPath' allows you to customize it
    this.proxy = this.connection.createHubProxy('connectionHub');

    this.proxy.on('messageReceived', (serverMessage) => this.onMessageReceived(serverMessage));

    this.connection.start().done((data: any) => {
      console.log('Connected to Connection Hub');
      this.sendMessage();
    }).catch((error: any) => {
      console.log('Connection Hub error:' + error);
    });
  }

  public sendMessage(): void {
    this.proxy.invoke('ClientMessage', 'My message')
      .catch((error: any) => {
        console.log('sending message error -> ' + error);
      });
  }

  private onMessageReceived(serverMessage: string) {
    console.log('New message received from Server: ' + serverMessage);
  }

}

别忘了声明jquery符号

declare var $: any;

现在您可以在组件中使用signalr服务:

constructor(private signalRService: SignalrService) { 
  this.signalRService.initializeSignalRConnection()
}

希望这能有所帮助

相关问题