How to use SignalR with Angular 2?

后端 未结 4 844
轮回少年
轮回少年 2021-02-06 09:12

How to use SignalR with Angular 2?

How to manually run change detection when receiving data from SignalR?

4条回答
  •  时光取名叫无心
    2021-02-06 09:55

    As far as examples go, there probably aren't any yet. Welcome to the beginning of a framework. But do keep checking over time because as popularity and adoption increases, there will sure to be many examples.

    As far as running change detection, that's a very vague question as angular2's change detection is now very different, and much improved.

    My approach is to just let angular2 handle it, and not trigger a manual change detection at all as most of the time Angular2 picks up on the change and re-renders the view.

    If that does not work, then the next step is to trigger .run() on the NgZone

    example:

    import {NgZone, Component} from 'angular2/core';
    
    @Component({...})
    export class MyComponent{
      myProperty: string = 'Hello';
      constructor(myService: MyService, ngZone: NgZone){}
    
      doSomething(){
        this.myService.doSomething().then(x => {
          this.ngZone.run(() => {
            this.myProperty = x;
          });
        });
      }
    }
    

    Again though, I have found that even working with asynchronous code, angular2 usually picks up on the change without using ngZone at all.

提交回复
热议问题