我正在尝试实现角度和信号器项目.我从
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); } }
但是我在= new HubConnection(this.base_url)中收到错误;使用此消息:类“HubConnection”的构造方法是私有的,只能在类声明中访问.
我需要你的帮助.谢谢.
解决方法
您必须使用HubConnectionBuilder().
import { Component,OnInit } from '@angular/core'; import { HubConnection,HubConnectionBuilder } from '@aspnet/signalr'; import { Message } from 'primeng/api'; @Component({ selector: 'app-root',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 }); }); } }