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:-
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.
FetchUserByUserid(userid:string) :Observable
Step 1: First import toPromise like the below.
import 'rxjs/add/operator/toPromise'
Step 2:
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:
FetchUserByUserid(userid:string) :Promise
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)
}