ASP.NET Signalr에 연결할 수있는 각도 형식 스크립트 라이브러리
출처 : NG2 신호 데모
데모 : 데모 (로드하는 데 시간이 더 걸릴 수 있습니다. 죄송합니다, Azure Free Tier :-))
NG CLI 예 : NG CLI 예제
npm install ng2-signalr jquery signalr --save
V5는 Angular V5에 대해 개발 된 첫 번째 버전입니다. 각도 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"
] , 연결을 생성하는 두 가지 방법이 있습니다.
이 접근법이 바람직합니다. 연결 설정이 진행되는 동안 기본 라우터 내비게이션 이벤트 (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' ] ;
}
} SignalR 인스턴스에서 Connect 메소드를 호출하여 클라이언트-서버 연결을 작성할 수 있습니다.
// inside your component.
constructor ( private _signalR : SignalR ) {
}
someFunction ( ) {
this . _signalR . connect ( ) . then ( ( c ) => {
//do stuff
} ) ;
}이 접근법에는 몇 가지 단점이 있습니다 : 대기 시간 :
2.0.6 버전에서 서버에 연결시 ConnectionStatus 변경 사항을 구독 할 수 있습니다. Forst Signalr에게 연결을 만들도록 요청합니다. 그런 다음 연결 객체에서 시작 방법을 호출하기 전에 관찰 가능한 상태를 구독 할 수 있습니다.
fyi : connect ()는 이제 createeconnection (). start ()의 속기입니다.
let conx = this . _signalR . createConnection ( ) ;
conx . status . subscribe ( ( s ) => console . warn ( s . name ) ) ;
conx . start ( ) . then ( ( c ) => {
...
} ) ; SingAlr을 두 가지 레벨로 구성 할 수 있습니다.
모듈 레벨은 일반적으로 기본 구성을 제공하는 곳입니다. 기본 허브 이름, 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 항상 연결 수준 당 신호를 구성 할 수 있습니다. 이를 위해서는 singalr.connect (옵션) 메소드를 호출하여 옵션 매개 변수를 유형 연결을 전달해야합니다. 무대 뒤에서 SignalR Connect Method는 제공된 옵션 매개 변수를 기본 (모듈) 구성과 함께 새로운 구성 객체로 병합하고이를 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 Method를 사용하면 위의 접근 방식의 첫 번째 단계를 건너 뛸 수 있습니다. 여기서 청취 방법은 BroadVasteventListener를 반환하여 구독 할 수 있습니다.
let onMessageSent$ = this . connection . listenFor ( 'ON_MESSAGE_SENT' ) ;
onMessageSent$ . subscribe ( ...ListenForRaw 메소드를 사용하는 경우 원래 데이터 양식 SignalR Client Callback을 캐스팅 할 수 있습니다. 여기서 청취 방법은 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'는 신호 클라이언트 연결의 조롱 된 구현을 요청할 수 있습니다. 인터페이스의 모의 연결은 실제 신호 연결과 동일하며 signarl.connect () 메소드에서 다시 돌아옵니다. 모의를 사용하여 특정 메소드 호출을 스파이하고 테스트에서 호출을 확인할 수 있습니다. 또한 Mockmanager 자체에서는 동작과 같은 '서버'를 트리거하는 방법을 찾을 수 있습니다. 오류 $와 상태 $ 속성 모두이를 위해 사용될 수 있으며 서버 오류 또는 ConnectionStatus 변경을 시뮬레이션 할 수 있습니다. Signarl Connection 라이프 사이클에 대한 자세한 내용은 공식 문서, 섹션 전송 연결 해제 시나리오를 참조하십시오. 또한 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.ForRoot (() => 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를 사용하여 모든 테스트를 컴파일하고 실행하십시오. 테스트 러너는 Autowatching 및 'Progress'로 테스트 리포터로 구성됩니다.