首页 > 解决方案 > 您可以在不调用 app.component 中的方法的情况下在服务中注入 Angular 10+ 中的 signalR

问题描述

因此,我遵循了一些教程,一旦您设置了集线器,其中一个常见主题C#就是调用类似于以下内容的服务:

private hubConnection: signalR.HubConnection = new signalR.HubConnectionBuilder()
.withUrl(`${environment.hub}contacts`)
.build();

constructor(private http: HttpClient) { 
}

public startConnection = () => 
  this.hubConnection
    .start()
    .then(() => console.log('Hub Connection started'))
    .catch(err => console.log('Error while starting connection: ' + err))
    

public addTransferContactDataListener = () => 
    this.hubConnection.on('transfercontactdata', (data) => {
        this.contacts = data.result // where the magic happens on the push
        console.log(data, 'Hub data transfer occuring');
    });

我担心的是,如果您尝试private hubConnection: signalR.HubConnection在构造函数中注入它会爆炸。即使您设置了连接构建器。这很重要,因为如果我想要四页或更多页subscribe怎么办?

我一直在做的是在 中设置服务,然后为然后app.component.ts调用方法。但这似乎是错误的。我试图让它在一个模块中注入,但它一直失败说它没有或其他东西。虽然它是可注入的,但您仍然必须调用它,并且在我的实践中,构造函数有时似乎被忽略了。startConnectionaddTransferContactDataListenerprovider

有没有人深入研究过调用并将其设置为注入并重用它? 就像“A”或“B”视图调用signalR服务一样,任何一个都可以自动让它运行构造函数或某个参数一次。我可能做错了什么。就像我说的,它有效。但我必须调用其中的方法,app.component.ts这样做感觉不对,而且很脆弱。

标签: angularsignalr.clientasp.net-core-signalr

解决方案


在 Angular 中使用 SignalR

我们的目标是创建一个服务,作为 Angular 和我们的 signalR 连接之间的中介。这种方法意味着我们需要解决两个一般性问题

  • 与 SignalR 连接
  • 设计一种与我们应用程序的其余部分交互的方法

角接口

我们的目标是能够在我们的应用程序中的任何位置注入我们的服务,并让我们的组件在我们的服务感兴趣的 signalR 集线器中发生事件时做出适当的反应

使服务可用

由于我们的服务可能会在任何地方使用,并且具有处理 connectionHub 的生命周期逻辑,如果尝试打开非关闭的连接将失败,我们可以使用的唯一注入器如下:

  • app.module.ts
  • @Injectable({providedIn: 'root'})

最简单的解决方案是使用@Injectable({providedIn: 'root'})装饰器,但是对于具有细微差别的内部生命周期的服务(例如 SignalR 服务),我更喜欢公开一个公共 API,以便我们只公开对我们的团队可以安全使用的方法。

公共接口

首先,让我们创建一个接口,我们可以使用该接口使 SignalR 服务在我们应用程序的其余部分中可用。但是,因为我们不能在 Angular 中提供接口,所以我们使用抽象类来代替。

公共 SignalR 接口


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

@Injectable()
export abstract class SignalRService {
  abstract getDataStream(): Observable<any>
}

我们的 SignalR 服务的开始


import {Subject, Observable} from 'rxjs';
import {SignalRService} from './signalr.service';
import {Injectable} from '@angular/core';

@Injectable()
export class PrivateSignalRService extends SignalRService {
  private _signalEvent: Subject<any>;

  constructor() {
    super();
    this._signalEvent = new Subject<any>();
  }

  getDataStream(): Observable<any> {
    return this._signalEvent.asObservable();
  }
}

现在我们有了注入的基本设置。我们在抽象类中描述我们希望为哪些服务可用的公共接口,将其视为接口,并在PrivateSignalRService

现在,我们剩下要做的就是告诉 Angular InjectorPrivateSignalRService在我们请求时提供SignalRService

app.module.ts


@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [{
    provide: SignalRService,
    useClass: PrivateSignalRService
  }],
  bootstrap: [AppComponent]
})
export class AppModule {
  // inject signal directly in module if you want to start connecting immediately.
  constructor(private signal: SignalRService) {
  }
}

将 SignalR 事件映射到主题事件

我们现在可以SignalRService在我们的应用程序中注入我们的,但是我们的 HubConnection 可能会随着时间的推移而增长,并且可能并非每个事件都与每个组件相关,因此我们创建了一个过滤器。

首先,我们创建一个枚举,它代表我们可能期望接收的每个不同的 HubConnection 事件。

信号事件类型.ts


export enum SignalEventType {
  EVENT_ONE,
  EVENT_TWO
}

接下来我们需要一个接口,以便我们知道调用时会发生什么getDataStream

信号事件

import {SignalEventType} from './signal-event-type';

export interface SignalEvent<TDataShape> {
  type: SignalEventType,
  data: TDataShape
}

更改我们的公共抽象类接口的签名

信号服务


@Injectable()
export abstract class SignalRService {
  abstract getDataStream<TDataShape>(...filterValues: SignalEventType[]): Observable<SignalEvent<TDataShape>>
}

PrivateSignalRService


@Injectable()
export class PrivateSignalRService extends SignalRService {
  private _signalEvent: BehaviorSubject<SignalEvent<any>>;

  constructor() {
    super();
    this._signalEvent = new BehaviorSubject<any>(null);
  }

  getDataStream<TDataShape>(...filterValues: SignalEventType[]): Observable<SignalEvent<TDataShape>> {
    return this._signalEvent.asObservable().pipe(filter(event => filterValues.some(f => f === event.type)));
  }

}

与 SignalR 连接

注意:此示例使用@aspnet/signalr包。

观察以下变化PrivateSignalRService

@Injectable()
export class PrivateSignalRService extends SignalRService {
  private _signalEvent: Subject<SignalEvent<any>>;
  private _openConnection: boolean = false;
  private _isInitializing: boolean = false;
  private _hubConnection!: HubConnection;

  constructor() {
    super();
    this._signalEvent = new Subject<any>();
    this._isInitializing = true;
    this._initializeSignalR();
  }

  getDataStream<TDataShape>(...filterValues: SignalEventType[]): Observable<SignalEvent<TDataShape>> {
    this._ensureConnection();
    return this._signalEvent.asObservable().pipe(filter(event => filterValues.some(f => f === event.type)));
  }

  private _ensureConnection() {
    if (this._openConnection || this._isInitializing) return;
    this._initializeSignalR();
  }

  private _initializeSignalR() {
    this._hubConnection = new HubConnectionBuilder()
      .withUrl('https://localhost:5001/signalHub')
      .build();
    this._hubConnection.start()
      .then(_ => {
        this._openConnection = true;
        this._isInitializing = false;
        this._setupSignalREvents()
      })
      .catch(error => {
        console.warn(error);
        this._hubConnection.stop().then(_ => {
          this._openConnection = false;
        })
      });

  }

  private _setupSignalREvents() {
    this._hubConnection.on('MessageHelloWorld', (data) => {
      // map or transform your data as appropriate here:
      this._onMessage({type: SignalEventType.EVENT_ONE, data})
    })
    this._hubConnection.on('MessageNumberArray', (data) => {
      // map or transform your data as appropriate here:
      const {numbers} = data;
      this._onMessage({type: SignalEventType.EVENT_TWO, data: numbers})
    })
    this._hubConnection.onclose((e) => this._openConnection = false);
  }

  private _onMessage<TDataShape>(payload: SignalEvent<TDataShape>) {
    this._signalEvent.next(payload);
  }

}

现在,当您第一次请求时,getDataStream如果没有打开的连接,服务将尝试创建 signalR 连接,因此您不再需要在AppModule构造函数中注入服务。

监听组件中的事件

  • 示例一感兴趣EVENT_ONE
  • 示例二感兴趣EVENT_TWO

示例-one.component.ts


@Component({
  selector: 'app-example-one',
  template: `<p>Example One Component</p>`
})

export class ExampleOneComponent implements OnInit, OnDestroy {
  subscription!: Subscription;
  constructor(private signal: SignalRService) {
  }

  ngOnInit(): void {
    this.subscription = this.signal.getDataStream<string>(SignalEventType.EVENT_ONE).subscribe(message => {
      console.log(message.data);
    })
  }
  
  ngOnDestroy() {
    this.subscription.unsubscribe();
  }

}

示例-two.component.ts


@Component({
  selector: 'app-example-two',
  template: `<p>Example Two Component</p>`
})
export class ExampleTwoComponent implements OnInit, OnDestroy {
  subscription!: Subscription;

  constructor(private signal: SignalRService) {
  }

  ngOnInit(): void {
    this.subscription = this.signal.getDataStream<string[]>(SignalEventType.EVENT_TWO).subscribe(message => {
      message.data.forEach(m => console.log(m));
    })
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }

}

ExampleOneComponent现在ExampleTwoComponent仅当 HubConnection 中接收的事件是每个组件的适当类型时才接收事件。

最后的笔记

此示例代码没有强大的错误处理功能,仅演示了我们将 signalR 与 Angular 集成所采用的通用方法。

您还需要确定管理本地持久性的策略,因为主题将仅显示任何新传入的消息,例如,当您在应用程序中导航时,它将重置您的组件。

资源

我在这里包含了一个小型 MVP 设置


推荐阅读