user13195568
user13195568

Reputation:

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?

Upvotes: 0

Views: 161

Answers (2)

AlleXyS
AlleXyS

Reputation: 2598

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);
   });
}

Upvotes: 1

Bon Macalindong
Bon Macalindong

Reputation: 1320

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();
  }

Upvotes: 0

Related Questions