Search code examples
angulartypescriptrxjsrxjs6rxjs-pipeable-operators

GAPI and Angular 7 issue


I have request to google drive using gapi:

getFolders(folderId: string): Observable<{ id: string, name: string }[]> {
    const promise = gapi.client.drive.files.list({
      fields: 'incompleteSearch,nextPageToken,files(id,name)',
      q: `'${folderId}' in parents`,
    }).then((res) => {
      return JSON.parse(res.result.files);
    });
    return from(promise);
  }

then I try to show this data in component: .ts file ngOnInit:

this.data$ = this.googleDriveService.getFolders(rootFolderId)
        .pipe(
          map((files) => {
            debugger;
            return files.map(file => ({ id: file.id, header: file.name, content: '', imageUrl: this.defaultImageUrl }));
          }),
          takeUntil(this.destroy$),
        );

and html file:

  <mat-grid-tile *ngFor="let elem of (data$ | async)">
    <app-card (input)="returnCartItem(elem)" (click)="goto(elem.header, elem.id)"></app-card>
  </mat-grid-tile>

The problem is that data$ always empty. I added debugger to map to check maybe something wrong with there, but it never goes in map function. From response, I get 2 files, so res.result.files isn't empty;


Solution

  • The problem was in gapi (google API). More info here I created private method inObservable

    private inObservable(promise) {
        return from(
          new Promise((resolve, reject) => {
            this.zone.run(() => {
              promise.then(resolve, reject);
            });
          })
        );
      }
    

    And wrap my request into it

    const promise = gapi.client.drive.files.list({
          fields: 'incompleteSearch,nextPageToken,files(id,name)',
          q: `'${folderId}' in parents`,
        }).then((res) => {
          return JSON.parse(res.result.files);
        });
    return inObservable(promise);