Search code examples
typescriptfirebase-realtime-databaseangularfire2

firebase thenable reference return handling


i am using angularfire2 and making a push call to store a object. it looks like below:

Click handler

assignCode(){
    this.ddlSvc.assignCoupon(this.selItem.key, coupon).then(
      (resp) =>  {
                      console.log("user created with:" + resp)
                      const alert = this.core.createAlert('Confirmation', 'Coupon Assgined to customer!')
                      alert.present()

                 }
    )
  }

angular service making call to firebase

assignCoupon(key:string, coupon:Coupon){
    return this.db.list('/users/' + key + '/coupons').push(coupon)
  }

It works fine when the calling client user has the required permissions to push to this node. However, we are testing a case where calling client does not have the permissions. currently, when we fire this case we get all the error on the UI in a very ugly manner rather a nice popup as we are not handling it. So, how do we handle error part? as it is a thenable reference so on click handler function there is no . ".catch" to handle.


Solution

  • If you go to the definition of ThenableReference (in Visual Studio Code, you would press Ctrl-T and then type ThenableReference), you should see something like this:

      interface ThenableReference
        extends firebase.database.Reference,
          PromiseLike<any> {}
    

    The part we care about is the PromiseLike<any>. If you jump to definition on that, you should see this:

    interface PromiseLike<T> {
        /**
         * Attaches callbacks for the resolution and/or rejection of the Promise.
         * @param onfulfilled The callback to execute when the Promise is resolved.
         * @param onrejected The callback to execute when the Promise is rejected.
         * @returns A Promise for the completion of which ever callback is executed.
         */
        then<TResult1 = T, TResult2 = never>(onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): PromiseLike<TResult1 | TResult2>;
    }
    

    Notice that then accepts an optional second callback that is called in case of error. You should be able to use that in place of the catch method.