我已经在Angular6中开发了一个项目。需要开发一个用于实时聊天的部分。为此,我在asp.net核心Web Apiproject中使用SignalR。现在,我想在Angular项目中使用此Web Api参考。
我正在使用this链接。
但是,在App.Component.ts中提供Web Api URL时,却出现以下错误:
类“ HubConnection”的构造函数是私有的,并且只能访问
在类声明中。
应用Component.ts:
import { HubConnection } from '@aspnet/signalr';
import { Message } from 'primeng/api';
export class AppComponent implements OnInit {
public _hubConnection: HubConnection;
msgs: Message[] = [];
constructor() {
}
ngOnInit() {
this._hubConnection = new HubConnection('http://localhost:1874/notify'); // getting error on this line.
编辑:尝试下面的代码:-
修改后的App.Component.ts:
import { HubConnection } from '@aspnet/signalr';
import * as signalR from '@aspnet/signalr';
import { Message } from 'primeng/api';
export class AppComponent implements OnInit {
public _hubConnection: HubConnection;
msgs: Message[] = [];
constructor() {
}
ngOnInit() {
this._hubConnection = new signalR.HubConnectionBuilder()
.withUrl('http://localhost:1874/notify')
.configureLogging(signalR.LogLevel.Information)
.build();
错误:
加载失败
http://localhost:1874/notify/negotiate:对飞行前请求的响应
未通过访问控制检查:
响应中的“ Access-Control-Allow-Credentials”标头为“
当请求的凭据模式为“包含”时,必须为“ true”。
因此,不允许访问源'http://localhost:4200'。的
XMLHttpRequest发起的请求的凭据模式为
由withCredentials属性控制。
最佳答案
他们将SignalR Client HubConnection
的构造函数更改为不再允许您在客户端构造函数中传递路由,并将HubConnection
构造函数设为私有以强制执行更改。相反,您需要使用HubConnectionBuilder
,如下所示:new HubConnectionBuilder().withUrl("/YOURROUTEHERE").build();
您将需要在标题中导入HubConnectionBuilder,如下所示:import { HubConnection, HubConnectionBuilder } from '@aspnet/signalr';
如果有帮助,我还刚刚发布了针对@ aspnet / signalr 1.0.2,RxJs 5.5.6和Angular 6的RxSignalR示例的更新。请查看ReactiveChat component作为示例。