typescript - Angular 5 + SignalR (DefinitelyTyped) - ไม่พบชื่อ '$'
ฉันกำลังพยายามใช้ SignalR ในแอปพลิเคชัน Angular 5 ของฉัน
ฉันติดตั้งชนิดข้อมูลที่เข้มงวดเหล่านี้จาก DefinitelyTyped:
npm install --save @types/jquery
npm install --save @types/signalr
Typescript ใน packages.json ของฉันแสดงเวอร์ชัน 2.5.3
ตอนนี้ฉันกำลังพยายามใช้มันแบบนี้:
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();
}
}
คอมไพเลอร์แจ้งข้อผิดพลาดดังต่อไปนี้:
error TS2304: Cannot find name '$'.
...แม้ว่า Intellisense จะสามารถค้นหา $.hub:
ถ้าฉันลองเพิ่ม declare var $ :any; เข้าไปในไฟล์ของฉัน มันก็สามารถคอมไพล์ได้ แต่ฉันก็ได้ข้อผิดพลาดอีกข้อในคอนโซลของเบราว์เซอร์: $.hubConnection ไม่ใช่ฟังก์ชัน.
ฉันกำลังพลาดอะไรไปหรือเปล่า?
คำตอบ #1
ในการใช้ SignalR ใน Angular คุณต้องทำขั้นตอนเหล่านี้:
ติดตั้งแพ็กเกจ jquery, signalr โดยใช้ npm:
npm install signalr
npm install jquery
เพิ่มประเภท:
npm install --save @types/jquery
npm install --save @types/signalr
เพิ่มสคริปต์ไปยัง angular-cli.json
"apps": [{
"scripts": [
"../node_modules/jquery/dist/jquery.min.js",
"../node_modules/signalr/jquery.signalR.min.js"
],
}]
และในบริการคุณต้องเพิ่ม:
declare var $: any;
ตัวอย่างโค้ด Angular ง่ายๆ:
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);
});
}
}
