我要求使用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
不是空的;
问题出在gapi(谷歌API)。更多信息here我在onObservable中创建了私有方法
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);
您将getFolders()
转换为可观察对象,因此您必须订阅它以开始从中获取数据。
this.googleDriveService.getFolders(rootFolderId).pipe(...).subscribe();
我认为使用async的方式有问题,请试试这个:
<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>
我认为问题在于,由于您的异步管道,在加载异步数据之前会尝试渲染内部元素。您可以执行一个简单的解决方法,为异步数据提供引用变量,并在引用变量就绪后呈现内部内容
<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