ASP.NET Signalrに接続できるAngular TypeScriptライブラリ
出典:NG2 SignalRデモ
デモ:デモ(ロードに時間がかかる場合があります。ごめんなさい、Azure Free Tier :-))
ng CLIの例:ng CLIの例
npm install ng2-signalr jquery signalr --save
V5は、Angular V5に対して開発された最初のバージョンです。 Angular V4ユーザーはV2.2.1を使用する必要があります。
内部app.module.ts
import { SignalRModule } from 'ng2-signalr' ;
import { SignalRConfiguration } from 'ng2-signalr' ;
// >= v2.0.0
export function createConfig ( ) : SignalRConfiguration {
const c = new SignalRConfiguration ( ) ;
c . hubName = 'Ng2SignalRHub' ;
c . qs = { user : 'donald' } ;
c . url = 'http://ng2-signalr-backend.azurewebsites.net/' ;
c . logging = true ;
// >= v5.0.0
c . executeEventsInZone = true ; // optional, default is true
c . executeErrorsInZone = false ; // optional, default is false
c . executeStatusChangeInZone = true ; // optional, default is true
return c ;
}
@ NgModule ( {
imports : [
SignalRModule . forRoot ( createConfig )
]
} )
// v1.0.9
const config = new SignalRConfiguration ( ) ;
config . hubName = 'Ng2SignalRHub' ;
config . qs = { user : 'donald' } ;
config . url = 'http://ng2-signalr-backend.azurewebsites.net/' ;
@ NgModule ( {
imports : [
SignalRModule . configure ( config )
]
} ) Angular-cli.json内
"scripts" : [
"../node_modules/jquery/dist/jquery.min.js" ,
"../node_modules/signalr/jquery.signalR.js"
] , 接続を作成する2つの方法が存在します。
このアプローチが望ましいです。デフォルトのルーターナビゲーションイベント(NavigationStart/End)に簡単に頼って、接続の確立が進行中にユーザーを忙しくしておくことができます。次に、接続を直接注入し、より簡単な単体テストを容易にします。セットアップには3つのステップが含まれます。
// 1. if you want your component code to be testable, it is best to use a route resolver and make the connection there
import { Resolve } from '@angular/router' ;
import { SignalR , SignalRConnection } from 'ng2-signalr' ;
import { Injectable } from '@angular/core' ;
@ Injectable ( )
export class ConnectionResolver implements Resolve < SignalRConnection > {
constructor ( private _signalR : SignalR ) { }
resolve ( ) {
console . log ( 'ConnectionResolver. Resolving...' ) ;
return this . _signalR . connect ( ) ;
}
}
// 2. use the resolver to resolve 'connection' when navigation to the your page/component
import { Route } from '@angular/router' ;
import { DocumentationComponent } from './index' ;
import { ConnectionResolver } from './documentation.route.resolver' ;
export const DocumentationRoutes : Route [ ] = [
{
path : 'documentation' ,
component : DocumentationComponent ,
resolve : { connection : ConnectionResolver }
}
] ;
// 3. then inside your component
export class ChatComponent {
private _connection : SignalRConnection ;
constructor ( route : ActivatedRoute ) {
}
ngOnInit ( ) {
this . connection = this . route . snapshot . data [ 'connection' ] ;
}
} Client-Server接続の作成は、SignalRインスタンスのConnectメソッドを呼び出すことで実行できます。
// inside your component.
constructor ( private _signalR : SignalR ) {
}
someFunction ( ) {
this . _signalR . connect ( ) . then ( ( c ) => {
//do stuff
} ) ;
}このアプローチにはいくつかの欠点があります:waittime:
バージョン2.0.6以降、サーバーに接続すると、ConnectionStatusの変更を購読できます。 forstあなたはsignrrに接続を作成するように依頼します。次に、接続オブジェクトで、開始メソッドを呼び出す前に、観察可能なステータスをサブスクライブできます。
参考までに:connect()は、createconnection()。start()の速記になり、ステータスの変更を購読せずに意味します
let conx = this . _signalR . createConnection ( ) ;
conx . status . subscribe ( ( s ) => console . warn ( s . name ) ) ;
conx . start ( ) . then ( ( c ) => {
...
} ) ; 2つの異なるレベルでSingalrを構成できます。
モジュールレベルは、通常、デフォルトの構成を提供する場所です。これは、デフォルトのHubname、ServerURL、QS(クエリ文字列パラメーター)、およびトランスポートで合格した場合です。アプリケーションのどこかで、Singalr.Connect()メソッドがパラメーターなしで呼び出されると、このデフォルトの構成が使用されます。
import { SignalRModule } from 'ng2-signalr' ;
import { SignalRConfiguration , ConnectionTransport } from 'ng2-signalr' ;
// <= v1.0.9
const config = new SignalRConfiguration ( ) ;
config . hubName = 'Ng2SignalRHub' ; //default
config . qs = { user : 'donald' } ;
config . url = 'http://ng2-signalr-backend.azurewebsites.net/' ;
// Specify one Transport: config.transport = ConnectionTransports.longPolling; or fallback options with order like below. Defaults to best avaliable connection.
config . transport = [ ConnectionTransports . webSockets , ConnectionTransports . longPolling ] ;
@ NgModule ( {
imports : [
SignalRModule . configure ( config )
]
} )
...
Signalr . connect ( ) ; //HERE: module level configuration is used when trying to connect 接続ごとのレベルでSignrRをいつでも構成できます。このためには、singalr.connect(options)メソッドを呼び出し、型接続のオプションパラメーターを渡す必要があります。舞台裏では、SignalR Connectメソッドは、提供されたオプションパラメーターをデフォルト(モジュール)構成と新しい構成オブジェクトにマージし、それをSignalR BackEndに渡します。
import { SignalRModule } from 'ng2-signalr' ;
import { IConnectionOptions , SignalR } from 'ng2-signalr' ;
let options : IConnectionOptions = { hubName : 'MyHub' } ;
Signalr . connect ( options ) ; // 1.create a listener object
let onMessageSent$ = new BroadcastEventListener < ChatMessage > ( 'ON_MESSAGE_SENT' ) ;
// 2.register the listener
this . connection . listen ( onMessageSent$ ) ;
// 3.subscribe for incoming messages
onMessageSent$ . subscribe ( ( chatMessage : ChatMessage ) => {
this . chatMessages . push ( chatMessage ) ;
} ) ;Listenforメソッドを使用する場合、上記のアプローチの最初のステップをスキップできます。ここでは、聞きた方法がbroadvasteventlistenerを返します。それをサブスクライブできます。
let onMessageSent$ = this . connection . listenFor ( 'ON_MESSAGE_SENT' ) ;
onMessageSent$ . subscribe ( ...listenforrawメソッドを使用する場合、元のデータフォームSignalRクライアントコールバックをキャストできます。ここでは、listenメソッドは、broadvasteventlistenerの[]を返します。
let onMessageSent$ = this . connection . listenForRaw ( 'ON_MESSAGE_SENT' ) ;
onMessageSent$ . subscribe ( ( data : any [ ] ) => ... . ) ; // invoke a server side method
this . connection . invoke ( 'GetNgBeSpeakers' ) . then ( ( data : string [ ] ) => {
this . speakers = data ;
} ) ;
// invoke a server side method, with parameters
this . connection . invoke ( 'ServerMethodName' , new Parameters ( ) ) . then ( ( data : string [ ] ) => {
this . members = data ;
} ) ; this . connection . status . subscribe ( ( status : ConnectionStatus ) => {
this . statuses . push ( status ) ;
} ) ; // start/stop the connection
this . connection . start ( ) ;
this . connection . stop ( ) ;
// listen for connection errors
this . connection . errors . subscribe ( ( error : any ) => {
this . errors . push ( error ) ;
} ) ; NG2-Signalrには、単体テストを簡単に書くことができ、コードの数行であるSignarlMockManagerを使用するためのコンポーネントが特別に構築されています。 「Signarlmockmanager」は、signalrクライアント接続の模擬実装を尋ねることができ、その模擬プロパティを使用してください。インターフェイスのモック接続は、signarl.connect()メソッドから戻ってくる実際の信号接続と同じです。モックを使用して特定のメソッド呼び出しをスパイし、テストでの呼び出しを確認できます。また、モックマネージャー自体には、動作のような「サーバー」をトリガーする方法があります。エラー$ $とstatus $プロパティの両方を使用することができ、サーバーエラーまたはConnectionStatusの変更をシミュレートできます。 Signarl Connection Lifecycleの詳細については、公式ドキュメント、セクショントランスポート切断シナリオを参照してください。また、Mockmanagerのリスナープロパティは、RXJS被験者として返されたすべてのクライアントサーバーメソッドオブザーバーのコレクションを保持しています。これらの主題を使用して、ワイヤー上で送信されるサーバーメッセージをシミュレートできます。
it ( 'I want to simulate an error or status event, in my unit test' ,
inject ( [ ChatComponent ] , ( component : ChatComponent ) => {
connectionMockManager . errors$ . next ( 'An error occured' ) ; //triggers the connection.error.subscribe(() => {});
connectionMockManager . status$ . next ( ConnectionStatuses . slowConnection ) ; //triggers the connection.status.subscribe(() => {});
... .
} ) ) ;
it ( 'I want to simulate several ChatMessages received, in my unit test' ,
inject ( [ ChatComponent ] , ( component : ChatComponent ) => {
let publisher = connectionMockManager . listeners [ 'OnMessageSent' ] ;
publisher . next ( new ChatMessage ( 'Hannes' , 'a message' ) ) ; //triggers the BroadcastEventListener.subscribe(() => {});
publisher . next ( new ChatMessage ( 'Hannes' , 'a second message' ) ) ; // ''
expect ( component . chatMessages ) . toEqual ( [
new ChatMessage ( 'Hannes' , 'a message' ) ,
new ChatMessage ( 'Hannes' , 'a second message' )
] ) ;
} ) ) ;詳細については、確かにライブデモ、ユニットテストセクションをご覧ください。
v2.0.6 <2.0.6から2.0.6のConnectionStatusリファクタリング
v2.0.0 1.0.xから2.0.0に進むには、いくつかの壊れた変更があります。
タイプの改名:
構成:
4。Signalrmodule.configure(c:singalrconfiguration)to signalr.foroot(()=> singalrconfiguration);
npm install jquery signalr expose-loader --save
//inside vendor.ts
import 'expose-loader?jQuery!jquery';
import '../node_modules/signalr/jquery.signalR.js';
{
'ng2-signalr' : 'node_modules/ng2-signalr/bundles/ng2-singalr.umd.(?min).js'
}
AF93C8777FB64C74F74A875E5DA60A168F410E06
バグが見つかった場合、または機能リクエストがある場合は、このリポジトリの問題セクションで報告してください。
プルリクエストは大歓迎です!
npm buildを使用して、コンパイルおよびビルドを使用します。 A /distフォルダーが生成されます。
dist/ng2-signalrに移動し、 npm publishを実行します。
## TODO:コードカバレッジ
npm test CMDを使用して、すべてのテストをコンパイルして実行します。
npm test CMDを使用して、すべてのテストをコンパイルして実行します。テストランナーは、テストレポーターとしてオートワッチと「進行状況」で構成されています。