I created a service via “ionic gen service myservices”
I created a page via “ionic gen page mytimeattendance”. This is page i have a slides #mySlider.
I need to use the service i have created to slide #mySlider using slideTo().
However, I am getting the following error:
“ERROR TypeError: Cannot read property ‘slideTo’ of undefined”
Welcome to the Ionic Forums.
Services shouldn’t be directly fiddling with the innards of components - it makes the app a big ball of goo that can’t be easily understood, tested, or maintained.
It also doesn’t make any logical sense for a service to know or care what anybody who has injected it is doing with it, because (in the vast majority of cases) one service instance is shared amongst many consumers of its services. That’s arguably a big part of what makes services useful.
So let’s say your service provides a list of teddy bears available for purchase. There is a BearBrowser
component that browses through some subset of bears. Both the notion of “what search criteria am I currently filtering the entire list of available bears by” and “which of the available bears am I looking at” belong to BearBrowser
, not BearService
.
So how I would structure this would be as follows:
interface Bear {...}
interface BearCriteria {...}
class BearService {
availableBearsByCriteria(crit: BearCriteria): Observable<Bear[]> {...}
}
class BearBrowser {
criteria = new FormControl();
availableBears: Bear[] = [];
constructor(private mama: BearService) {
this.criteria.valueChanges()
.pipe(switchMap(crit => this.mama.availableBearsByCriteria(crit)))
.subscribe(bears => {
this.availableBears = bears;
// move slider here as needed
});
}
}