1

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

- app.component.ts
- app.html
- sub.component.ts
- sub.html
- data.service.ts

sub.component作为指令包含在app.component. app.compontent注入data.service,我可以从app.component.

问题

以前,我可以从组件中的函数更新视图上的进度条。现在该函数在它自己的服务中,我如何更新用户关于服务中长时间运行(递归)方法的进度?我假设我必须将服务的进度传递给app.componentor sub.component,但这意味着如何完成?

4

2 回答 2

6

您可以使用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));
  }
}
于 2016-02-13T22:55:15.107 回答
0

您需要从组件(或两个组件)订阅服务。

您可以在引导程序上提供服务(并且所有组件都可以使用它)

bootstrap(App, [YourService]);

或者通过提供在组件中提供它:

@Component({selector: "cmp", provide: [YourService]})

看看这个例子: https ://plnkr.co/edit/d4jIDQ4lSuXUDttKFAS6?p=preview

于 2016-02-13T22:52:47.157 回答