What is Promises in Angular?

This article discusses the usage of Promises and Obserable in angular.We can either use Promises or Observable to build HTTP services.By default returns an observable.It also discusses about how to handle error in observable and also the handling of errors in promises. for eg:-

FetchUserByUserid(userid:string) :Observable{
return this._http.get("http://localhost:12100/api/users/" + userid)
       .map((response:Response)=>response.json())
       .catch(this.handleerror);
}
In the above code, we are using get method to fetch users based on userid,if you analyze get method ,by default it returns an observable.

How to return Promises ,instead of an Observable?

Step 1: First import toPromise like the below. import 'rxjs/add/operator/toPromise'
Step 2:

 FetchUserByUserid(userid:string) :Promise
  {
    return this._http.get("http://localhost:12100/api/users/" + userid)
    .map((response:Response)=>response.json())
    .toPromise()
.catch(this.handleerror);
    }
handleError(error:Response)
{
    console.error(error)
    return Observable.throw(error);
   }
  Previously for Observable ,we use Observable.throw as return of handleerror.But now we are using promises,so we will call
  new method "handlePromiseerror()" like the below
handlePromiserror(error:Response)
    {
        console.error(error)
    throw(error);
}
}
come let us use that fetchuserbyuserid method in userservice in our usercomponent. Previously for Observable we use subscribe method,but now we are using a promise,so we have to use .then Usercomponent.ts:

ngOninit()
{
let userid:string=this._activatedRoute.snapshot.params['code']
this._userservice.fetchuserbyuserid(userid)
.then(
               (userdata)=>{
                    if(userdata==null)
                    {
	                    this.status="user not exist"
                    }
	                    else
                    {
	                    this.user=userdata;
                    }
                },
                (error)=>
                {
                         this.status="service error.pls try again"
                         console.error(error)
                }
}

the above .then method has 2 parameters one is 'onfulfilled' and other is 'onrejected' when promise is accepted then 'onfullfilled' is called otherwise it calls 'onrejected' instead of above we can also write like the below.

this._userservice.fetchuserbyuserid(userid)
.then((userdata)=>
{
            if(userdata==null)
            {
            this.status="user not exist"
            }
            else
            {
            this.user=userdata;
            }
            }   
}
.catch(error)=>
{
this.status="service error.pls try again"
console.error(error)
}