Gokulanathan KN
Gokulanathan KN

Reputation: 23

Error: "Uncaught (in promise): [object Object]

An error occurs when I try to post a GET method to a rest api, but in postman it is working perfectly.

 public cartview() {
    let localaccesstoken = localStorage.getItem('token');
    let apiUrl = this.urlService.apiUrl+'cart?access_token='+localaccesstoken;
    console.log(apiUrl);

    return new Promise((resolve, reject) => {
        console.log("test : "+apiUrl);
        this.http.get(apiUrl)
          .subscribe(res => {
            console.log("w3cert Url : "+JSON.stringify(res));            
            console.log(resolve(res));
          }, (err) => {
            console.log('w3cert : '+reject(err));
        });
    });

In console log it shows an api. I copied that api and posted in postman and it is working, but in the app it shows this error:

Error: "Uncaught (in promise): [object Object]"

Upvotes: 1

Views: 4608

Answers (2)

ASghostKI
ASghostKI

Reputation: 168

I think the problem is from where you call your cartview() function you should call it with then AND catch both :

cartview().then(res => {
    console.log(res)
}).catch(err => {
    console.error(err)
})

Upvotes: 1

Francisco
Francisco

Reputation: 2056

Change your method into something like this :

 public cartview() {
   let localaccesstoken = localStorage.getItem('token');
   let apiUrl = this.urlService.apiUrl+'cart?access_token='+localaccesstoken;
   console.log(apiUrl);
   return this.http.get(apiUrl).pipe(
     tap(res => console.log(res))
   ).toPromise() <--- rxjs wraps the observable in a Promise for you
 });

I figure the above should be somthing like a service method. So then in your component (or where you want to catch the promise) you can call the .then() method:

...cartview().then(res => console.log(res)).catch(err => console.error(err))

From the above code, I can see you're not working well with observables / promises and also, you're logging the resolve/reject methods itself, not it's results.

Upvotes: 1

Related Questions