来自服务的 Angular2 更新模板
Angular2 Update Template from Service
我是 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
.
中的点击事件调用服务
问题
以前,我可以通过组件中的函数更新视图上的进度条。现在该函数在其自己的服务中,我如何向用户更新服务中 long-运行(递归)方法的进度?我假设我必须将服务的进度传递给 app.component
或 sub.component
,但这意味着如何完成?
您需要从组件(或两个组件)订阅服务。
您可以在 bootstrap 上提供服务(它将对您的所有组件可用)
bootstrap(App, [YourService]);
或者通过 provide:
在组件中提供它
@Component({selector: "cmp", provide: [YourService]})
看看这个例子:
https://plnkr.co/edit/d4jIDQ4lSuXUDttKFAS6?p=preview
您可以使用 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));
}
}
我是 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
.
问题
以前,我可以通过组件中的函数更新视图上的进度条。现在该函数在其自己的服务中,我如何向用户更新服务中 long-运行(递归)方法的进度?我假设我必须将服务的进度传递给 app.component
或 sub.component
,但这意味着如何完成?
您需要从组件(或两个组件)订阅服务。
您可以在 bootstrap 上提供服务(它将对您的所有组件可用)
bootstrap(App, [YourService]);
或者通过 provide:
在组件中提供它@Component({selector: "cmp", provide: [YourService]})
看看这个例子: https://plnkr.co/edit/d4jIDQ4lSuXUDttKFAS6?p=preview
您可以使用 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));
}
}