I have a component class as EventSchedulePage
.It extends HandleStorageService
abstract
class as shown below.You can see that there is a method named showInvalidTokenAlert()
on this subclass.I have to call this method each and every component(This method gives a token based error message to the user).So can you tell me how to implement or redesign my classes to cater this situation? 'cause I don't like to put showInvalidTokenAlert()
on each and every component.I would like to keep that method's implementation on a single place.
Subclass
export class EventSchedulePage extends HandleStorageService {
constructor() {
super();
}
showInvalidTokenAlert() {
//show alert
}
}
abstract class
export abstract class HandleStorageService {
result: string = '';
constructor() {
}
}
You could create a
BasePage
, and put there all the shared code.The key is that the
BasePage
receives an instance of the injector from the subclass, so you could obtain any instance that you need from it (like theAlertController
instance that you need to show an alert message). By using the get methods, each instance will be obtained from the injector just once.And then in all the pages from your app:
This way is super easy to add some more helper methods.
It is definitely more MVCS-like (Model-View-Controller-Service) to handle that in the controller. But that is a widely taken approach.
If you want to go for it, @suraj's answer is my personal recommendation.
Handling alerts on the controller is certainly possible. Keep reading.
event-schedule-page.service.ts
home.controller.ts
To follow up, you can use custom error classes or separate functions to throw / handle your errors.
You can create a separate provider class with the
showInvalidTokenAlert()
functionSet it in app.module.ts as provider in case you require as singleton
Inject in any component you require.