简体   繁体   English

Angular5:在我的组件中恢复Promise Statut服务

[英]Angular5 : recover promise statut service in my component

I lost all my hair on this point. 在这一点上,我失去了所有的头发。 I use : Angular5 cli + AngularFire2 我使用:Angular5 CLI + AngularFire2

1° In my component my function destroyUnicorn call my service updateUnicorn1 . 1°在我的组件中,我的函数destroyUnicorn调用我的服务updateUnicorn1

2° As i want to know if the request works, i made a Promise in my service updateUnicorn1. 2°我想知道请求是否有效,所以我在服务updateUnicorn1中做了一个承诺

3° I am unable to listen if the request resolve or reject omg ^^. 3°如果请求解决或拒绝了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. 如果请求不起作用,我想显示console.log(“ error”)并在我的组件中执行另一个函数,另一方面, 我想显示console.log(“ success”)并在我的组件中执行另一个函数 。 。

(But console.log works in the service) (但是console.log在该服务中有效)

My Component.ts : 我的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 首先,您的组件很棒: 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 再见

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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