Handle errors with http services

Hello,

i’am using ionic 2 recently and its awesome!

But i have some problems on handling errors on http-services/providers which
are created with the ionic cli generator.

Service example:

@Injectable()
export class TestService {
  user: User = null;

  constructor(public http: Http) {}
  

  load() {
    if (this.user) {
      // already loaded data
      return Promise.resolve(this.user);
    }

    // don't have the data yet
    return new Promise(resolve => {
      // We're using Angular Http provider to request the data,
      // then on the response it'll map the JSON data to a parsed JS object.
      // Next we process the data and resolve the promise with the new data.
      this.http.get('dummy/user.json')
        .map(res => res.json())
        .subscribe(data => {
          // we've got back the raw data, now generate the core schedule data
          // and save the data for later reference
          this.user = data;
          resolve(this.user);
        });
    });
  }

First question
Why are the generated services expose a promise with “resolve” and not expose a observable?
Is this the recommended way to create this kind of services?

Second question
My usecase is to call a server and when the server is not available to
show an alert.

this.TestService.load()
        .then(() => {
          //Success
        })
        .catch(err => {
            //show alert
        });

But when i try to call a server which is not available to test the alert behavior, on error it not
goes to the catch case!

How can i handle http request errors properly to give users a feedback?

Got the solution?
I guess I will go for doing Observables

I did this:
In the provider

 return this.http
     .post(this.baseURL + this.apiVersion + 'users/login', body, options)
      .map(res => res.json())
      .toPromise();

In the service:

this.api.login(loginForm)
    	.then(data => {
   		console.log(data);
    	})
 	.catch(error => { console.log(error) });

Hope it works for others. Dont know if it is the right way.

subscript takes 3 callbacks, success, fail, complete

subscribe(
  (value) => ... // success,
  (err) => ... // fail
  () => ... // complete
)
8 Likes

.subscribe(response => {

},onerror=>{ ‘Error menssage’});