Error Message: Angular 5 with SignalR (DefinitelyTyped) - '$' Not Found in Typings

I am currently working on implementing SignalR into my Angular 5 application.

To do this, I added the following TypeScript type definitions from DefinitelyTyped:

npm install --save @types/jquery
npm install --save @types/signalr

The version of Typescript in my packages.json is 2.5.3.

Here is how I'm attempting to use SignalR:

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();
    }
}

However, the compiler is showing the following error:

error TS2304: Cannot find name '$'.

Interestingly, intellisense can recognize $.hub:

https://i.sstatic.net/X1kgP.png


I tried adding declare var $ :any; to my file which resolved the compile error, but resulted in another error in the browser's console:

$.hubConnection is not a function
.

Am I overlooking something crucial?

Answer №1

If you want to incorporate SignalR into Angular, follow these steps:

Begin by installing the jquery and signalr packages using npm:

npm install signalr
npm install jquery

Next, add the necessary types:

npm install --save @types/jquery 
npm install --save @types/signalr

Include the scripts in your angular-cli.json file:

"apps": [{
    "scripts": [
        "../node_modules/jquery/dist/jquery.min.js",
        "../node_modules/signalr/jquery.signalR.min.js"
    ],
}]

In your service file, ensure to declare $ as any:

declare var $: any;

Here's a simple example of Angular code for SignalR integration:

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); 
            });
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error: The AppModule encountered a NullInjectorError with resolve in a R3InjectorError

I encountered a strange error in my Angular project that seems to be related to the App Module. The error message does not provide a specific location in the code where it occurred. The exact error is as follows: ERROR Error: Uncaught (in promise): NullInj ...

Typescript Support in Goland IDE for HTML Documents

I'm currently utilizing Go for my programming tasks, and I prefer the Goland IDE developed by Jetbrains. Is there a way for me to incorporate typescript into my .html template files that contain a mix of HTML, CSS, and JS? Your assistance is much ap ...

What is the best way to manage the connections in my D3 tree chart?

I've been working on customizing a tool from an open source library called angular-d3-tree, but I'm struggling with getting the links to connect properly in my D3 tree structure. This is what my current tree layout looks like: https://i.stack.im ...

Having conflicting useEffects?

I often encounter this problem. When I chain useEffects to trigger after state changes, some of the useEffects in the chain have overlapping dependencies that cause them both to be triggered simultaneously instead of sequentially following a state change. ...

typescript error: Unable to access properties of an undefined value

I am facing an issue while trying to import a class in my TypeScript code. I have tried using private classA = new ClassA, but it's not working as expected and the result is undefined. Here is my code: import JWT from "../Utils/JWT" import { ...

Encountering a node-sass error when running npm update

Some time ago, I incorporated node-sass into a project. However, now whenever I run npm update or npm install in a different project that does not use node-sass, I encounter the following error: npm ERR! <a href="/cdn-cgi/l/email-protection" class="__c ...

Circular dependency in Angular between two components

I'm currently working on an Angular 7 project that involves managing different entities, like Cars and Students. The structure of the application components can be represented by the following hierarchy: Cars Cars/CreateCar (dialog) Students Studen ...

I need to print out a table, but when I preview the print, I want to rotate the entire page for better visibility

Is there a way to rotate the print review using CSS and HTML? I am facing issues as the CSS styles do not seem to apply properly on it. Can someone help me solve this problem? ...

Tips for retrieving the most recent number dynamically in a separate component without needing to refresh the page

Utilizing both the Helloworld and New components, we aim to store a value in localStorage using the former and display it using the latter. Despite attempts to retrieve this data via computed properties, the need for manual refreshing persists. To explore ...

Issues with ng2-pdf-viewer arising in Angular versions 12 and above

Issue Detected If 'pdf-viewer' is an Angular component with the 'src' input, ensure it is included in this module. If 'pdf-viewer' is a Web Component, add 'CUSTOM_ELEMENTS_SCHEMA' to '@NgModule.schemas' of ...

Looking for guidance on integrating REST API consumption features into Ionic Framework 3.x?

It's been a long time since I last used the ionic framework. The version I worked with was 1, where every page created with Ionic Creator had its own controller for adding JavaScript code to consume my REST framework. Now that I've downloaded th ...

The concept of callback function overloading using generic types in TypeScript

Is there a way to define a callback type in TypeScript that can accept a variable number of generic type arguments while keeping the number of arguments fixed? For instance: export interface CustomFn { <T1>(value1: T1): boolean <T1,T2>(va ...

Issue: NG04002 encountered post migration from Angular to Angular Universal

Having recently created a new Angular app and converted it to Angular Universal, I encountered an issue when running the project using npm run dev:ssr. The error displayed in the terminal is as follows: ERROR Error: Uncaught (in promise): Error: NG04002 Er ...

typescript throwing an unexpected import/export token error

I'm currently exploring TypeScript for the first time and I find myself puzzled by the import/export mechanisms that differ from what I'm used to with ES6. Here is an interface I'm attempting to export in a file named transformedRowInterfac ...

The blur event in Angular Material's mat-date-range-input does not trigger if the End Date is not selected

I am currently utilizing Angular 15 along with Angular Material 14. The code for the DatePicker control is shown below. <mat-form-field class="datepicker-widget" appearance="fill"> <mat-date-range-input [formGroup]="d ...

What is the best way to send data to the ng2-smart-table renderComponent using an HTTP request?

I am working with a table that includes a custom component in one of its cells. There is also a service that provides the data to display in this table. The custom component I have implemented includes a select feature, so the column in the table looks lik ...

npm pack is taking an unusually long time to complete

I'm currently using npm version 5.6.0 and when running the command npm pack -ddd, which enables maximum verbosity, I am experiencing extremely long wait times. It seems to hang during the prepack phase, possibly due to the tar zip bundledDependencies ...

Having trouble with installing Vue CLI?

I am encountering issues while attempting to set up VueJS. I am currently utilizing Bash on Ubuntu on Windows node -v v15.12.0 npm -v 7.6.3 Initially, I attempted the following: npm install -g @vue/cli However, this resulted in various warnings and ...

Incorporating external scss files into next.js (react) for seamless loading

Encountering an error when trying to load SaSS files from zeit node_modules\@zeit\next-css\node_modules\mini-css-extract-plugin\dist\index.js:21} = _webpack2.default; ^TypeError: Cannot destructure property `createHash` of &a ...

Angular2 - receiving real-time notifications about service data updates

I've been facing a challenge with getting a chart component to update when a new line is added by another component. I attempted to use a service to connect the two and believed that utilizing BehaviorSubject would be the solution, but it seems like t ...