类'HubConnection'的构造方法是私有的,只能在类声明中访问

Iba*_*408 8 signalr angular

我正在尝试实现角度和信号器项目.我从Medium获取样本

我已经安装了所有必需的软件包,并在app.component.ts中输入以下代码:

import { Component, OnInit } from '@angular/core';
import { HubConnection } from '@aspnet/signalr';

import { Message } from 'primeng/api';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'PROJECT TITLE';
  base_url = 'http://localhost:8081/';

  hubConnecton: HubConnection;
  msgs: Message[] = [];

  constructor() { 

  }

  ngOnInit(): void {
    this.hubConnecton = new HubConnection(this.base_url);
  }
}
Run Code Online (Sandbox Code Playgroud)

但是我收到= new HubConnection(this.base_url);这条消息的错误:Constructor of class 'HubConnection' is private and only accessible within the class declaration.

在此输入图像描述

我需要你的帮助.谢谢.

小智 16

您必须使用HubConnectionBuilder().

import { Component, OnInit } from '@angular/core';
import { HubConnection, HubConnectionBuilder } from '@aspnet/signalr';
import { Message } from 'primeng/api';

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

  public _hubConnecton: HubConnection;
  msgs: Message[] = [];

  constructor() { }

  ngOnInit(): void {
    this._hubConnecton = new HubConnectionBuilder().withUrl("http:/:localhost:1874/notify").build();
    this._hubConnecton
      .start()
      .then(() => console.log('Connection started!'))
      .catch(err => console.log('Error while establishing connection :('));

    this._hubConnecton.on('BroadcastMessage', (type: string, payload: string) => {
      this.msgs.push({ severity: type, summary: payload });
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 请直接发布代码,而不是代码图片! (2认同)