1// -------------------------------------------------------------------------------------
2// codes for component
3import { JustAService} from '../justAService.service';
4@Component({
5 selector: 'app-cute-little',
6 templateUrl: './cute-little.component.html',
7 styleUrls: ['./cute-little.component.css']
8})
9export class CuteLittleComponent implements OnInit {
10 s: JustAService;
11 a: number = 10;
12 constructor(theService: JustAService) {
13 this.s = theService;
14 }
15
16 ngOnInit() {
17 this.s.onSomethingHappended(this.doThis.bind(this));
18 }
19
20 doThis() {
21 this.a++;
22 console.log('yuppiiiii, ', this.a);
23 }
24}
25// -------------------------------------------------------------------------------------
26// codes for service
27@Injectable({
28 providedIn: 'root'
29})
30export class JustAService {
31 private myFunc: () => void;
32 onSomethingHappended(fn: () => void) {
33 this.myFunc = fn;
34 // from now on, call myFunc wherever you want inside this service
35 }
36}
37