GAPI和Angular 7问题

时间:2019-04-21 23:33:48

标签: angular typescript rxjs rxjs6 rxjs-pipeable-operators

我有请求使用gapi前往Google驱动器

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

然后我尝试在组件中显示此数据: .ts文件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$),
        );

和html文件:

  <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>

问题是data$始终为空。我在debugger中添加了map,以检查其中是否有问题,但是在map函数中却没有。从响应中,我得到2个文件,所以res.result.files不为空;

4 个答案:

答案 0 :(得分:0)

您将getFolders()变成了一个可观察的对象,因此您必须订阅它才能开始从中获取数据。

this.googleDriveService.getFolders(rootFolderId).pipe(...).subscribe();

答案 1 :(得分:0)

我认为使用异步方式存在问题,请尝试以下方法:

<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>

答案 2 :(得分:0)

我认为问题在于,由于您使用了异步管道,因此在加载异步数据之前尝试渲染内部元素。您可以做一个简单的解决方法,为异步数据提供一个参考变量,并在参考变量准备好后呈现内部内容

<ng-container *ngIf="data$ | async as data">
    <mat-grid-tile *ngFor="let elem of data | async">  //note it is not data$
        <app-card (input)="returnCartItem(elem)" (click)="goto(elem.header, elem.id)"> 
        </app-card>
    </mat-grid-tile>
</ng-container

答案 3 :(得分:0)

问题出在gapi(google API)中。更多信息here 我创建了私有方法inObservable

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

然后将我的请求包装到其中

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