简体   繁体   中英

Angular 2 return data from arrow function

I have the following code

getEnquiryWithId(id: number) {
    let enquiryStore = this.db.transaction('enquiries', 'readonly').objectStore('enquiries');
    let index = enquiryStore.index('enquiries');
    let request = index.get(id);
    return request.onsuccess = (event) => {
      return event.target.result;
    }
  }

which i'm trying to use in a pipe

transform(value: number): string {
    let request = this.dbStore.getEnquiryWithId(value);
    let result = request();
  }

I get an error saying Cannot invoke an expression whose type lacks a call signature .

Note: that I cannot rely RxJs subjects here as my transform function needs to return something, as its a pipe. How do I make this work?

The title misleading. You don't want data to be returned from an arrow function (which is trivially possible), but you want your arrow function to be synchronously executed - which is not possible as it's a callback that will be called by the JS engine.

As others mentioned you can return a Promise in your function that resolves as soon as the the inner query succeeds:

getEnquiryWithId(id: number) {
  let enquiryStore = this.db.transaction('enquiries', 'readonly').objectStore('enquiries');
  let index = enquiryStore.index('enquiries');
  let request = index.get(id);
  return new Promise((resolve, reject) => {
    request.onsuccess = (event) => {
      resolve(event.target.result);
    };
    request.onerror = (event) => {
      reject(request.errorCode);
    };
  }
}

If you want to display the result of a promise you could simply use AsyncPipe . It's not necessary to write an own transform function.

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