简体   繁体   中英

Angular Service subscribe not allowed in component

I have a service that's returning some code:

Here is the code for the service and for the component:

Code in service:

async readdir() {
    try {
      const ret = await Filesystem.readdir({
        path: '',
        directory: FilesystemDirectory.Documents
      });
      return ret;
    } catch (e) {
      console.error('Unable to read dir', e);
    }
  }

Code in Component

getdirdata() {
    this.filesystemService.readdir().subscribe(data => {
      console.log(data);
    });
  }

My issue is that it doesn't like subscribe...

I get:

Property 'subscribe' does not exist on type 'Promise<ReaddirResult[]>'.

How can I fix this?

Your result type is a Promise, not an Observable to can subscribe on it. For Promises use then() to get the result.

getdirdata() {
   this.filesystemService.readdir().then(data => {
      console.log(data);
   });
}

More about Promise

you can convert the promise result into an observable using from operator

import { from } from 'rxjs';
async readdir() {
    try {
      const ret = await Filesystem.readdir({
        path: '',
        directory: FilesystemDirectory.Documents
      });
      return from(ret);
    } catch (e) {
      console.error('Unable to read dir', e);
    }
  }

then you can subscribe for the answer, because readdir() result will be an Observable:

getdirdata() {
   this.filesystemService.readdir().subscribe(data => {
      console.log(data);
   });
}

Subscribe is one of the methods of an Observable, however in your case you're using a promise.

You should be using .then to get the resolved data.

getdirdata() {
    this.filesystemService.readdir().then(data => {
      console.log(data);
    });
  }

You can even use async await pattern likeso:

async getdirdata() {
    const data = await this.filesystemService.readdir();
  }

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