Returning http response for error


#1

Trying to get http response to return even when an error occurs.

login( creds ){

  var headers = new Headers();
  headers.append('Content-Type', 'application/x-www-form-urlencoded');

  return new Promise(resolve => {
    this.http.post( this.baseUrl+'/login', creds, {
        headers: headers
    })
      .map(res => res.json())
      .subscribe(
        data => {
        this.data = data;
        this.saveToken(data.api_token);
        resolve(this.data);
        },
        error => { resolve({success: false}) }
        ).catch( resolve({success: false}) );
  });
 }

Here is the call

this.auth.login( creds ).then(function( res ){
     if(res.success){
         t.gotoStart();
     } else {
         console.log(failed);
         t.failedAlert('Login Failed', 'Either your email or password was incorrect.')
     }
 });

#2

I don’t understand why you’re returning a promise instead of an observable, but if you really want to do that, I’d look into toPromise.


#3

I don’t mind changing to observables. This is the first API call I’ve gotten to. Any tips or can you point me in the right direction?


#4

Does this article look helpful?


#5

Using the default observable you get from the http request

login( creds ){
  var headers = new Headers();
  headers.append('Content-Type', 'application/x-www-form-urlencoded');

    return this.http.post( this.baseUrl+'/login', creds, {
        headers: headers
    })
      .map(=>res.json())
      .subscribe(
        data => {
           this.data = data;
           this.saveToken(data.api_token);
           return this.data;
        } );
  });
 }

Subscribe here in the calling component

this.auth.login(creds)
  .subscribe(
    (data: any) => {
      console.log('Login Success', data)
      this.nav.setRoot(ListStuffPage, {});
    },
  (err) => console.log("Error Loging In:", JSON.parse(err._body).description),
  () => { console.log("error") }
  );

#6

Sweet, thanks @aaronksaunders, that’s exactly what I ended up with.