// -------------------------------------------------------------------------------------
// codes for component
import { JustAService} from '../justAService.service';
@Component({
selector: 'app-cute-little',
templateUrl: './cute-little.component.html',
styleUrls: ['./cute-little.component.css']
})
export class CuteLittleComponent implements OnInit {
s: JustAService;
a: number = 10;
constructor(theService: JustAService) {
this.s = theService;
}
ngOnInit() {
this.s.onSomethingHappended(this.doThis.bind(this));
}
doThis() {
this.a++;
console.log('yuppiiiii, ', this.a);
}
}
// -------------------------------------------------------------------------------------
// codes for service
@Injectable({
providedIn: 'root'
})
export class JustAService {
private myFunc: () => void;
onSomethingHappended(fn: () => void) {
this.myFunc = fn;
// from now on, call myFunc wherever you want inside this service
}
}
// In the service
export class simpleService{
private subject = new Subject<any>();
constructor() { }
// Service message commands
// Read Service Data
onReadData(data: any){
this.subject.next(data);
}
// Send Service Data
onSendData() {
return this.subject.asObservable();
}
}
// In the component you want to send the data to
dataSubscription: Subscription;
constructor(private simpleService: SimpleService){
this.dataSubscription = this.simpleService.onSendData().subscribe( async (data) => {
// do whaterver you want with the incoming data
console.log('incoming data: ', data);
});
}