1

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. 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. app.compontent injects data.service and I can call the service from a click event in app.component.

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?

Fiona
  • 1,211
  • 3
  • 16
  • 20

2 Answers2

6

You can use EventEmitter to pass values to the component. 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));
  }
}
Sasxa
  • 40,334
  • 16
  • 88
  • 102
0

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

Vlado Tesanovic
  • 6,369
  • 2
  • 20
  • 31
  • Sure, no problem. Be careful about one thing: If you provide service in application bootstrap - it is same object of that class in all components where you subscribe. If you provide it per component, you are creating new object each time. – Vlado Tesanovic Feb 14 '16 at 09:48