Daniel
Daniel

Reputation: 1755

How to bind service variable with component Angular 2?

I have an variable: public tick:number; in service.

The service has injection of another service Timer. It is launched like as:

class Service {

constructor(public timer: TimerService)

}

public sendSmsExect(){
   // Main sending
}

public sendSms(){

    this.timer.run().subscribe((tick => { if(tick == 30) { sendSmsExect(); } }));

}

}

Component:

class MyComponent {

    public constructor(public service Service){}

    public sendSms(){
       this.service.sendSms();
    }

}

Problem: I need to get access to tick varaible in template:

{{tick}} 

Do I really think that I need to subscribe to tick also in component and define the same variable tick:

public sendSms(){
   this.service.sendSms().subscribe((tick) => this.tick = tick );
}

Upvotes: 3

Views: 7832

Answers (1)

Pankaj Parkar
Pankaj Parkar

Reputation: 136184

You could consider sharing tick variable value from service using Subject observable. By making it observable you don't need to subscribe it an unwrap the value of tick from it. You need to use | async pipe on HTML, which will take care of unwrapping value of tick and displaying it on HTML.

Code

//don't miss below import
import { Subject } from 'rxjs/Subject';

class MyService {
  tick: Subject < number > ();
  constructor(public timer: TimerService) {}

  sendSmsExect() {
    // Main sending
  }
  tickObservable() {
    return this.tick.asObservable();
  }

  public sendSms() {
    this.timer.run().subscribe(tick => {
      this.tick.next(tick);
      if (tick == 30) {
        sendSmsExect();
      }
    );
  }
}

Component

//don't miss below import
import { Observable } from 'rxjs/Observable';

class MyComponent {
    tick: Observable<number>();
    public constructor(public service: MyService ){}

    sendSms(){
       this.service.sendSms();
    }
    ngOnInit(){
       this.tick = this.service.tickObservable();
    }
}

Html

{{tick | async}}

Upvotes: 4

Related Questions