【问题标题】:How to connect Signal R with Angular 6 and Asp.net MVC api?如何将 Signal R 与 Angular 6 和 Asp.net MVC api 连接起来?
【发布时间】:2019-01-03 06:41:06
【问题描述】:

我有一个拍卖应用程序,我需要在其中显示每个用户的实时出价。 我想使用的技术是 Angular 6 用于前端,Signal R 用于实时通信,Asp.net MVC 作为后端 api。 我尝试使用 @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
}

下面是 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 { }

以下是 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}`);
    }
}

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

【问题讨论】:

  • 您的具体问题是什么?

标签: asp.net-mvc signalr angular5 angular6 signalr-hub


【解决方案1】:

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

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

2) 由于您现在使用的是 signalr 包,因此当您尝试在 Angular 组件中实例化新的 HubConnection 时,您将无法访问 HubConnectionBuilder

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

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

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

[HubName("HubName")]    
public class MyHubClass: Hub

您很可能必须在 .cs 文件的顶部包含以下内容: using Microsoft.AspNet.SignalR.Hubs;

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

this.hubConnection.createHubProxy("yourHubName");

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

我在这里关注了example 来学习如何设置调用事件和监听服务器事件。是的,它是 Angular 2,但是 Signalr 的功能在我的 Angular 7 应用程序中仍然可以正常工作。

如果这会给您带来一些问题,请参阅我的其他答案 here 以获取有关 jQuery 和 signalR 的进一步解释

【讨论】:

    【解决方案2】:

    您需要使用 ng2-signalR,因为您没有使用 ASP.NET Core。您还需要将 /signalr/ 附加到客户端上的 URL。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-08
      • 2019-01-09
      • 2019-10-17
      • 2014-01-08
      • 2017-04-03
      • 1970-01-01
      • 1970-01-01
      • 2020-10-26
      相关资源
      最近更新 更多