如何将 Signal R 与 Angular 6 和 Asp.net MVC api 连接起来?

Sha*_*wla 2 asp.net-mvc signalr signalr-hub angular5 angular6

我有一个拍卖应用程序,我需要在其中显示每个用户的实时出价。我想使用的技术是前端的 Angular 6、实时通信的 Signal R 和后端 api 的 Asp.net MVC。我尝试使用@aspnet/signalR 以及 ng2-signalR

以下是我的一些代码:

App.component.ts

import { Component, Injectable } from '@angular/core';
import { SignalR, SignalRConnection, ISignalRConnection, BroadcastEventListener } from '../../node_modules/ng2-signalr';
import { Route, ActivatedRoute, Resolve } from '@angular/router';
import { BidService } from './app.service';
import { BidBlotter } from './Bid.Model';
import * as signalR from '@aspnet/signalr';
import { HubConnection } from '@aspnet/signalr';

// import '~/signalr/hubs';
declare var $: any;

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  private _connection: SignalRConnection;
  public _hubConnection: SignalRConnection;

  constructor(
    private _signalR: SignalR,
    private _bidservice: BidService,
    public route: ActivatedRoute) {
  }
  private _hubConnection1: HubConnection | undefined;
  ngOnInit() {
this.getBids(1);
    this.connectToSignalR();
    }

private server: any; // used to call server
  // $.connection.testSignalRHub.client
  private client: any; // used to receive calls from server
  // $.connection.testSignalRHub
  private hub: any; // hub itself
  private hub1: any; // hub itself
  connectToSignalR() {

    jQuery.getScript('http://localhost:52106/signalr/hubs', () => {
this.server.broadcastCommonData = (data: any) => {
        alert(1);
        // self.commonData = data;
      };


    })
    // if you need to call the server hub method - use server variable:
    //this.server.broadcastCommonData(this.commonData);
  }
  bidDetails = [];
  bidBlotter: BidBlotter;

  title = 'app';
  QuickBid(amount) {
    // this._signalR.connect().then((c) => {
    debugger
    var abc = amount;
    var data = Object.assign({}, this.bidBlotter, {
      Amount: abc
    });
    this._bidservice.SaveBidDetails(data).subscribe(() => {
      // this.myfun();
      // this.getBids(1);
      debugger
      this.connection.invoke('BroadcastCommonData').then((data: string[]) => {
        // this.speakers = data;
      });

    });
    // });
  }

  id: number = 1;

  getBids(id) {
    this._bidservice.GetBidList(id).subscribe((response) => {
      var data = JSON.parse(JSON.stringify(response));
      this.bidDetails = data;
    })
  }

 private connection: any;
  private proxy: any;
  private ulr: any;

  myfun() {
 this.connection = $.hubConnection("http://localhost:52106");
    let conx = this._signalR.createConnection();
    conx.status.subscribe((s) => console.log(s.name));
    debugger
    conx.start().then((c) => {
      console.log("Connected");
    });
    let onMessageSent$ = new BroadcastEventListener<any>('ON_MESSAGE_SENT');
    this.connection.listen(onMessageSent$);
    onMessageSent$.subscribe((chatMessage: any) => {
      debugger
      alert("success");
      // this.chatMessages.push(chatMessage);
    });
    }
  public sendMessage(): void {
    debugger
    this.proxy.invoke('PostToClient', alert(1))
      // .subscribe(()=>{
      //   debugger;
      // })
      .catch((error: any) => {
        console.log('SendMessage error -> ' + error);
      });
  }


}

import { EventEmitter, NgZone, OnDestroy } from "@angular/core";
import * as jQuery from "jquery";
import { Observable, Observer, ReplaySubject, Subject } from "rxjs";

export enum HubConnectionState {
  Connecting = 1,
  Connected = 2,
  Reconnecting = 3,
  Disconnected = 4
}
Run Code Online (Sandbox Code Playgroud)

以下是 App.Module.ts 文件

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { Http, Response, Headers,RequestOptions } from '@angular/http';
import { AppComponent } from './app.component';
import { SignalRModule } from 'ng2-signalr';
import { SignalRConfiguration } from 'ng2-signalr';
import { RouterModule, Routes} from '@angular/router';
// import { ConnectionResolver } from './app.component';
import { BidService } from './app.service';
import { HttpClient, HttpHeaders, HttpClientModule } from '@angular/common/http';
import { ConnectionResolver } from './app.component.resolver';


export function createConfig(): SignalRConfiguration {
  const c = new SignalRConfiguration();
  c.hubName = 'RequestLog';
  // c.qs = { user: 'donald' };
  // c.url = 'http://localhost:52106/';
  c.url = 'http://localhost:52106/';
  c.logging = true;

  // >= v5.0.0
  c.executeEventsInZone = true; // optional, default is true
  c.executeErrorsInZone = false; // optional, default is false
  c.executeStatusChangeInZone = true; // optional, default is true
  return c;
}

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    RouterModule.forRoot([]),
    SignalRModule.forRoot(createConfig),
    HttpClientModule

  ],
  providers: [BidService],
  bootstrap: [AppComponent]
})
export class AppModule { }
Run Code Online (Sandbox Code Playgroud)

下面是 App.service.ts

import { Injectable } from '@angular/core';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';
import 'rxjs/add/Observable/of';
import { HttpClient, HttpHeaders, HttpClientModule } from '@angular/common/http';
import { BidBlotter } from './Bid.Model';

@Injectable()
export class BidService {

    constructor(private http: HttpClient) { }

    private BaseUrl = "http://localhost:52106/";

    SaveBidDetails(bidblotter: BidBlotter) {
        return this.http.post(this.BaseUrl + `api/Bid/SaveBid`, bidblotter);
    }

    GetBidList(id : number) {
        return this.http.get(this.BaseUrl + `api/Bid/GetListByID/${id}`);
    }
}
Run Code Online (Sandbox Code Playgroud)

还有一些文件,如 app.component.html 、route、model 等,但我认为这些文件足以详细说明信号 r 处理。任何帮助,将不胜感激.....

pol*_*pol 5

我只是经历了很多同样的挫折。我刚刚回答了另一篇文章,重点介绍了我使用 ac# .net 框架后端设置 angular 应用程序所经历的一些事情。

1) 该@aspnet/signalr包用于 .Net Core。对于 .Net Framework,您需要signalr包 ( npm install signalr)。

2)由于您现在正在使用该signalr包,因此HubConnectionBuilder尝试在您的角度组件中实例化一个新的 HubConnection 时,您将无法访问。

相反,当 signalr 脚本被执行时,它会将额外的事件附加到$您的代码中。注意:如果您在构建或编译时从 ts 文件中收到错误,请确保已包含来自 npm的@types/signalr@types/jquery

要设置新的集线器连接,请使用$.hubConnection("your-url-here/signalr"). 这将在运行时附加到您服务器的集线器。注意:我将此结果存储为hubConnection在我的角度组件中调用的变量

在您拥有 Hub 类的服务器代码(.cs 文件)上,您需要在类名上方添加: [HubName("YourHubName")]. 所以在你的情况下,你的 .cs 文件在顶部看起来像这样:

[HubName("HubName")]    
public class MyHubClass: Hub
Run Code Online (Sandbox Code Playgroud)

您很可能必须将其包含在 .cs 文件的顶部: using Microsoft.AspNet.SignalR.Hubs;

然后在你的 Angular 组件中设置一个代理以附加到服务器上的集线器在实例化新的 hubConnection 后的下一行,写:

this.hubConnection.createHubProxy("yourHubName");.

创建代理后,您可以附加侦听器以侦听从服务器发出的事件,或者您可以从 Angular 组件调用服务器函数。

我在这里学习了这个例子来学习如何设置调用事件和监听服务器事件。是的,它是 angular 2,但信号器的功能在我的 angular 7 应用程序中仍然有效。

见我对方的回答在这里对jQuery和signalR进一步解释,如果给你一些问题