0

我要求使用 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);
  }

然后我尝试在组件中显示这些数据:.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$总是空的。我添加debuggermap检查那里可能有问题,但它永远不会map发挥作用。从响应中,我得到 2 个文件,所以res.result.files不是空的;

4

4 回答 4

1

问题出在gapi(谷歌API)中。更多信息在这里 我创建了私有方法 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);
于 2019-05-06T09:19:30.137 回答
0

你变成getFolders()了一个 observable,所以你必须订阅它才能开始从中获取数据。

this.googleDriveService.getFolders(rootFolderId).pipe(...).subscribe();
于 2019-04-21T23:47:05.967 回答
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>
于 2019-04-22T07:41:45.807 回答
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
于 2019-04-23T18:20:52.663 回答