简体   繁体   中英

Angular5 : recover promise statut service in my component

I lost all my hair on this point. I use : Angular5 cli + AngularFire2

1° In my component my function destroyUnicorn call my service updateUnicorn1 .

2° As i want to know if the request works, i made a Promise in my service updateUnicorn1.

3° I am unable to listen if the request resolve or reject omg ^^. If the request doesn't work I want to display console.log("error") and execute another function in my component , on the other hand i want do display console.log("success") and execute another function in my component.

(But console.log works in the service)

My Component.ts :

destroyUnicorn(item){
    this.itemService.updateUnicorn1( {
        statut: "destroyed",
        id: item.id
    })
    .then(function() {
         console.log('success');

    }).catch(function(something) {
         console.log('error');
    });
};

My service.ts

    updateUnicorn1(item) {
          let self = this;

          let promise = new Promise((resolve, reject) => {
            self.itemDoc = self.afs.doc(`unicorns/${item.id}`);
            self.itemDoc.update(item)
            .then(resolve => {
                   console.log('all good');
            })
            .catch(reject => {
                  console.log('catch');
            });

        });  
       return promise;   
      }

Here is my boy !

First your component is marvellous so : Component.ts

destroyUnicorn(item){
    this.itemService.updateUnicorn1( {
        statut: "destroyed",
        id: item.id
    })
    .then(function() {
         console.log('success');

    }).catch(function(something) {
         console.log('error');
    });
};

Second: the problem is the promise structure : So let's do that:

updateUnicorn1(item) {
      var self = this;

      return new Promise((resolve,reject)=>{ 
        self.itemDoc = self.afs.doc(`unicorns/${item.id}`);
        self.itemDoc.update(item)
        .then(()=>{ 
            resolve({success :true}); 
        })
        .catch((err)=>{ 
            reject(err); 
        }); 
    }); 
  }

I Think the problem was the return. See you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM