2017-01-24 3 views
0

angle2のコンポーネントで有線の問題に直面するsignalr(外部読み込みスクリプト)を使用しようとしています。私の関数は、WebAPIから渡されている正しい情報でtypescriptで呼び出されていますが、それらのtypescript関数の中で宣言されたプロパティや関数を使用することはできません。私のWebAPIのから角2 - SignalRスコープのコンポーネントメンバー/メソッドにアクセスできない

、私は

IHubContext hubContext = GlobalHost.ConnectionManager.GetHubContext<CarBidHub>(); 
hubContext.Clients.All.NotifyManager_BidPlaced(message); 

のようにクライアントに通知していますこれは私が私が

を呼び出そうとしています

declare var jQuery: any; 
declare var moment: any; 
var hub = jQuery.connection.carBidHub; //declaring hub 
@Component({ 
    selector: 'live-auction', 
    templateUrl: '/auctions/live/live-auction.html' 
}) 
export class LiveAuctionComponent 
{ 
    ... 
    constructor(private notificationService: NotificationsService) 
    { 
    } 
    ... 

    private startHub(): void { 
      jQuery.connection.hub.logging = false; 

      hub.client.NotifyManager_BidPlaced = function (message:string) { 
       //this message is printed on all connected clients 
       console.log(message); 

       //but this line below throws an error on all members I am trying to access with "this." 
       this.notificationService.success('Information', message); 
      } 

      //this.notificationService is available here 

      //Start the hub 
      jQuery.connection.hub.start(); 
    } 
} 

のようにそれを定義している私の角度成分で通話を開始します

//call start hub method 
this.startHub(); 

ngAfterViewInit、OnInitおよびコンポーネントのコンストラクタですが、機能しません。

signalrの受信機がtypescript関数の中で定義されているので、外部から呼び出されたときに正しいコンテキストがない可能性があると推測できます。

私はこの NotifyManager_BidPlaced関数から宣言したメンバーにアクセスすることができました方法はありますか?

答えて

2

多くの例が同じ問題であります。経験則では、クラス内でキーワードfunctionを使用しないでください。これにより、thisコンテキストが現在の関数スコープのコンテキストに置き換えられます。 () => {}の表記を使用してください。

private startHub(): void { 
    jQuery.connection.hub.logging = false; 

    hub.client.NotifyManager_BidPlaced = (message:string) => { //here 
     this.notificationService.success('Information', message); 
    }; 

    jQuery.connection.hub.start(); 
} 
+0

魅力的なように働きました!私はそれが機能キーワードを使用して範囲を変更することは知らなかった、ありがとう:) –

+1

@AliBaigあなたは大歓迎です:)幸運 – PierreDuc

関連する問題