3

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 );
}

1 Answer 1

4

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}}
Sign up to request clarification or add additional context in comments.

8 Comments

@Daniel please refer to this article, there are many SO threads which you may find helpful :)
@Daniel about your solution, I'm still wondering, how tick value got available inside your component. Though the suggested way is preferred..
Here I get syntax error: tick: Subject < number > ();
Also where did you start: this.timer.run()?
And another error: TypeError: Cannot read property 'asObservable' of undefined at SmsService.tickObservable
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.