如何将服务变量与组件Angular 2绑定? [英] How to bind service variable with component Angular 2?

查看:130
本文介绍了如何将服务变量与组件Angular 2绑定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个变量:服务中的public tick:number;.

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

该服务已注入另一个服务Timer.像这样启动:

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

}

}

组件:

class MyComponent {

    public constructor(public service Service){}

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

}

问题:我需要访问模板中的刻度变量:

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

{{tick}} 

我真的认为我也需要在组件中同时订阅tick并定义相同的变量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 );
}

推荐答案

您可以考虑使用Subject observable共享服务中的tick变量值.通过使其可观察,您无需订阅它即可取消报价的价格变动.您需要在HTML上使用| async管道,这将用于解包tick的值并将其显示在HTML上.

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.

代码

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

组件

//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}}

这篇关于如何将服务变量与组件Angular 2绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆