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:


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

Example of Node-gallery used in isolation, displaying an error event with the message "ENOENT"

I am currently experiencing an issue with the node-gallery npm module. After installing dependencies inside the /example directory, I attempted to run the app. The result was a localhost:3000/gallery page, but upon the page fully loading, I encountered the ...

Utilizing Enum Lowercase as Index Key Type in TypeScript

Is there a way in TypeScript to use the lower case of an enum as an index key type? I have an enum defined as: export enum NameSet { Taxi = 'Taxi', Bus = 'Bus', Empty = '', } I want to define an object with keys based o ...

Exporting a Typescript class from one module and importing it into another module

I am encountering issues with my source tree structure, as outlined below: /project/ |- src/ |- moduleA |- index.ts |- classA.ts (which includes a public function called doSomething()) |- moduleB |- classB.ts Th ...

Fetching an image from a fixed storage location with the help of Express JS in Angular 2

Utilizing node js and express on the backend, I have a static folder filled with various images. My current task involves loading these images using angular 2 on the client side. Below is a snippet of my code: Backend side: app.use(express.static(__dirna ...

Retrieving user data from Ngrx store upon page refresh

Is it safe to retrieve user data from the database and store it after refreshing the page? Currently, I am getting the user ID from local storage in Guard and dispatching an action to retrieve the user data. Should I consider a different approach for thi ...

By utilizing custom typeRoots while continuing to export these types alongside the entry point

For my project setup, I employ rollup to bundle an associated index.d.ts (and index.js) for the entrypoint src/index.ts. Within the project structure, there exists a directory named src/types containing multiple .d.ts files. These types are globally acces ...

Problems with NPM Installation on Windows 7

While performing an NPM install on Windows 7, I encountered an error that I can't seem to resolve. C:\xampp\htdocs\dev4\nodejs\node_modules\jsdom\node_modules\contextify>node "C:\ Program Files (x86)& ...

Developing Angular dynamic components recursively can enhance the flexibility and inter

My goal is to construct a flexible component based on a Config. This component will parse the config recursively and generate the necessary components. However, an issue arises where the ngAfterViewInit() method is only being called twice. @Component({ ...

What is the best way to initiate the registration page through the @auth0/auth0-react library?

I've hit a roadblock in trying to automatically launch the sign-up (registration) page using @auth0/auth0-react. Previously, I would send mode which worked with auth0-js. So far, I have attempted the following without success: const { loginWithRedir ...

Why is it necessary to update npm each time I add a new library to my project?

It seems like every time I install a new library using npm, I encounter the same update message: Update available 5.6.0 → 5.8.0 Run npm i -g npm to update After updating as prompted, the cycle repeats itself with each new library installation. ...

TS - Custom API hook for making multiple API requests - incompatible type with 'IUseApiHook'

What is my objective? I aim to develop a versatile function capable of handling any type of API request for a frontend application. Essentially, I want to add some flair. Issue at hand? I find myself overwhelmed and in need of a fresh perspective to revi ...

The specified file ngx-extended-pdf-viewer/assets/pdf.js cannot be found

I have integrated the ngx-extended-pdf-viewer package in my Angular application using npm to enable the display of PDF content. According to the setup instructions, I have added the following configuration in my angular.json file: "assets": [ ...

Achieving the incorporation of multiple components within a parent component using Angular 6

Within parent.component.html The HTML code I have implemented is as follows: <button type="button" class="btn btn-secondary (click)="AddComponentAdd()">Address</button> <app-addresse *ngFor="let addres of collOfAdd" [add]="addres">< ...

Validating properties of a class using Typescript's Class-Validator

I tried using the class-validator decorator library for validation processes on my sample project. However, it doesn't seem to be working as expected. The sample project aims to create projects based on user inputs, and I'm attempting to validate ...

Modify associated dropdown menus

I am trying to create an edit form that includes dependent select fields (such as country, state, city). The issue I am facing is that the edit only works when I reselect the first option (car brand) because I am using the event (change) with $event. How c ...

Guide on properly specifying mapDispatchToProps in a component's props interface

In my project, I have a connected component utilizing mapStateToProps and mapDispatchToProps along with the connect HOC from react-redux. My goal is to create concise and future-proof type definitions for this component. When it comes to defining types fo ...

Creating a unique Elastic IP address for a single EC2 instance with the AWS CDK

I'm having an issue with my AWS CDK Stack where multiple Elastic IPs are being created for each public subnet in my VPC instead of just one. I only want one Elastic IP to be associated with a single EC2 instance. My simplified code snippet is as foll ...

Why am I unable to use a string as the src in next/image component?

After importing the Image module with the code import Image from "next/image";, I encountered an error that states: The type '{ src: string; }' cannot be assigned to type 'IntrinsicAttributes & ImageProps'. The type &apo ...

Heroku Application Experiencing Crashes Due to Absence of 'request-promise' Module

I am still a novice when it comes to MERN stack development (and programming in general). Currently, I am working on an app for a project using Heroku, and it seems like my proxy is encountering dependency issues. Below is the log from Heroku: 2020-04-20 ...

How can I capture the click event on the oktext in Ionic?

When using Ionic, I have a select button with options for okText and cancelText. The issue I am facing is that when I click on okText, the menu closes as expected due to this attribute. However, I am interested in implementing it through click events. Belo ...