服务中的Angular2更新模板

Fio*_*ona 1 angular2-services angular

我是Angular2的新手,开始编写一个所有方法所在的应用程序main.ts,然后该文件依次引用它的视图main.html.我将此应用程序重构为子组件和服务.所以,我现在有:

- app.component.ts
- app.html
- sub.component.ts
- sub.html
- data.service.ts
Run Code Online (Sandbox Code Playgroud)

sub.component作为指令包括在内app.component.app.compontent注入data.service,我可以通过点击事件调用该服务app.component.

问题

以前,我可以从组件中的函数更新视图上的进度条.现在该函数在自己的服务中,如何更新用户有关服务中长时间运行(递归)方法的进度?我假设我必须将服务的进度传递给app.componentsub.component,但这是怎么做的?

Sas*_*sxa 5

您可以使用EventEmitter将值传递给组件.在服务中创建发射器并在组件中订阅它.

// data.service.ts
class DataService() {
  progress = new EventEmitter();

  longRunningMethod() {
    this.progress.emit(value);
  }
}

// app.component.ts
class AppComponent() {
  constructor(service: DataService) {
    service.progress.subscribe(value => console.log(value));
  }
}
Run Code Online (Sandbox Code Playgroud)