Reputation: 10695
I'm trying to use SignalR in my Angular 5 application.
I installed these strong typed from DefinitelyTyped:
npm install --save @types/jquery
npm install --save @types/signalr
Typescript in my packages.json
shows version 2.5.3.
Now I'm trying to use it like this:
import { Injectable } from '@angular/core';
@Injectable()
export class SignalRService {
constructor() {}
public ConnectTo(url: string): void {
var hubConnection = $.hubConnection();
var hubProxy = hubConnection.createHubProxy('DashboardHub');
hubProxy.on('Example', (e: any) => {
console.log('worked');
});
hubConnection.start();
}
}
The compiler complains with the following:
error TS2304: Cannot find name '$'.
...even though intellisense can find $.hub
:
If I try adding declare var $ :any;
to my file, it compiles but I get another error in browser's console: $.hubConnection is not a function
.
Am I missing something?
Upvotes: 2
Views: 6612
Reputation: 126
To use SignalR in Angular you need to do these steps:
Install jquery, signalr packages using npm:
npm install signalr
npm install jquery
Add types:
npm install --save @types/jquery
npm install --save @types/signalr
Add scripts to angular-cli.json
"apps": [{
"scripts": [
"../node_modules/jquery/dist/jquery.min.js",
"../node_modules/signalr/jquery.signalR.min.js"
],
}]
And in service you need to add:
declare var $: any;
Simple Angular code example:
import { Injectable } from '@angular/core';
declare var $: any;
@Injectable()
export class SignalrService {
private connection: any;
private proxy: any;
private ulr: any;
constructor() {}
public startConnection(): void {
this.connection = $.hubConnection(this.url);
this.proxy = this.connection.createHubProxy('ProcessingHub');
this.connection.start().done((data: any) => {
console.log('Connected to Processing Hub');
this.sendMessage();
}).catch((error: any) => {
console.log('Hub error -> ' + error);
});
}
public sendMessage(): void {
this.proxy.invoke('SendMessage', 'test')
.catch((error: any) => {
console.log('SendMessage error -> ' + error);
});
}
}
Upvotes: 11