Ionic 2, how to show alert and do navigation in Service


#1

Hi, i am using service for getting data from the server. i want to know how to show alert in case of error for example : in case of error 404., 401 etc. I want to show alert in case of error and in some cases i want to navigate on next page on success, for example in case of successful login user can navigate on next page. Thanks.


#2

I realize that my opinion may not be widely shared, but I think this is a bad idea. I have services only deal with data, and not interact with the view layer at all. It is the page’s responsibility to handle all view layer activity.


#3

Thanks @rapropos, then how you handle error handling and navigation. Any type of help is appreciated. Do you have link to any tutorial. where error handling is done on page after getting data from services.


#4

Here is how I handle user authentication login/logout navigation. As for errors,

export function happyToastOptions(msg: string): ToastOptions {
  return {
    message: msg,
    duration: 3000,
    cssClass: 'happy-toast',
  };
}

export function errorToastOptions(msg: string): ToastOptions {
  return {
    message: msg,
    showCloseButton: true,
    closeButtonText: '閉じる',
    cssClass: 'sad-toast',
  };
}

.happy-toast .toast-container {
  background-color: green;
  color: white;
}

.sad-toast .toast-container {
  background-color: red;
  color: white;
}

class TypicalPage {
  doSomething(): void {
    this._service.fetchSomething().subscribe((thing) => {
      this.thing = thing;
      this._toasts.create(happyToastOptions('got thing')).present();
    }, (err) => {
      this._toasts.create(errorToastOptions('network error')).present();
    }
  }
}