简体   繁体   English

来自服务的Angular2更新模板

[英]Angular2 Update Template from Service

I'm new to Angular2, and started off writing an app where all methods were in main.ts , and that file in turn referenced its view in main.html . 我是Angular2的新手,因此开始编写一个应用程序,其中所有方法都位于main.ts ,而该文件又在main.html引用了其视图。 I refactored this app into subcomponents and services. 我将此应用程序重构为子组件和服务。 So, I now have: 所以,我现在有:

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

sub.component is included as a directive in app.component . sub.component作为指令包含在app.component app.compontent injects data.service and I can call the service from a click event in app.component . app.compontent注入data.service ,我可以通过app.component的click事件调用该服务。

The Question 问题

Previously, I could update a progress bar on the view from a function in the component. 以前,我可以通过组件中的功能更新视图上的进度条。 Now that the function is in its own service, how do I update the user on the progress of the long-running (recursive) method in the service? 现在,该函数位于其自己的服务中,如何在该服务中长期运行(递归)方法的进度上向用户更新? I assume I have to pass the progress from the service to app.component or sub.component , but how is this meant to be done? 我假设我必须将服务的进度传递给app.componentsub.component ,但这是怎么做的?

You can use EventEmitter to pass values to the component. 您可以使用EventEmitter将值传递给组件。 Create emitter in your service and subscribe to it in the component. 在您的服务中创建发射器,并在组件中进行订阅。

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

You need subscribe to service from component ( or both component ). 您需要从组件(或两个组件)订阅服务。

You can provide service on bootstrap ( and it will be available to all your components ) 您可以在引导程序上提供服务(它将对您的所有组件可用)

bootstrap(App, [YourService]);

Or to provide it in component with provide: 或通过提供来在组件中提供:

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

Take a look on this example: https://plnkr.co/edit/d4jIDQ4lSuXUDttKFAS6?p=preview 看一下此示例: https : //plnkr.co/edit/d4jIDQ4lSuXUDttKFAS6?p=preview

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM