Troubleshooting problem with GAPI and Angular 7

I made a request to Google Drive using the gapi library:

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 attempted to display this data in a 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 in the 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 issue is that the data$ always returns empty. I placed a debugger in the map function to check if there was an issue there, but it never reaches inside the map function. Despite receiving a response with 2 files, the res.result.files does not appear to be empty;

Answer №1

Encountered an issue with gapi (Google API). For further details, check out this link Implemented a private method inObservable

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

Wrapped the request within 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);

Answer №2

Transforming getFolders() into an observable now requires you to subscribe in order to receive data from it.

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

Answer №3

It seems like there might be an issue with the implementation of async in this code snippet. Here's a suggested revision:

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

Answer №4

It seems like the issue arises from the async pipe causing the inner elements to render before the async data is fully loaded. One way to overcome this is by using a simple workaround where you assign a reference variable to your async data and then render the inner content only when the reference variable is ready:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Leveraging SumoLogic for managing logs in Angular 2 and higher applications

Is it possible to integrate SumoLogic () into my Angular 2+ application? I've searched online but haven't come across anything indicating that it can be done. Can anyone provide some guidance on this? ...

Testing with Jasmine: Modifying a specific property in a service

I have a component spec file that utilizes the CalendarService. Within the CalendarService, there are properties such as weekNames, monthNames, and monthLongNames, which are arrays of strings. The CalendarService contains numerous methods, and I am looking ...

Is dart2js trying to compile CSS files?

It seems like the compiler dart2js is attempting to compile the CSS files from bootstrap. I tried searching online for a solution, but couldn't find any helpful information. I'm not really sure what keywords to use in my search. My previous proj ...

Top tips for accessing and modifying an immutable object within a component retrieved from an RXJS/NGRX store in Angular

This week we successfully updated our Angular v9 app to v11 and RXJS v6.6 with minimal issues. However, due to the store being in freeze mode, we are encountering errors when trying to update the store in certain areas of our code. While most of the issue ...

What is the best way to switch a set of buttons on and off?

I have a set of primary buttons, each with a group of nested secondary buttons. When a primary button is clicked, I want only its corresponding secondary buttons to be displayed. If the same primary button is clicked again, all its secondary buttons shoul ...

Show images from an array of base64 image data

I am currently facing an issue while trying to display images in base64 format within a RadListView component. Within the loop of the component, I have the following code snippet: let base64ImageSource = new ImageSource; base64ImageSource = fromBase64(re ...

What is the process for testing responses with errors in Jasmine?

I am currently testing a part of the code that looks like this: ngOnChanges() { this.searchCriteria$ = this.bookingService.getSearchCriteria(this.booking.id).pipe( catchError((err) => { this.error$ = of(err); return EMPTY; }) ); } I ...

Converting a string to a number is not functioning as expected

I am facing a problem with an input shown below. The issue arises when trying to convert the budget numeric property into thousands separators (for example, 1,000). <ion-input [ngModel]="project.budget | thousandsSeparatorPipe" (ngModelChange)="projec ...

How to retrieve various data points from a service and pass them to a component in

Utilizing an httpmodule to fetch data from the backend, I am faced with a challenge. While loading data in the service and returning it to the component, I also need to send a status code along with it. Unfortunately, the Data model is already set and cann ...

Ways to determine if the type is an enum in TypeScript

Consider the following string enum type: export enum UserRole { admin = "admin", active = "active", blocked = "blocked" } I'm looking to determine whether a specific string emulates this enum type. How can I achieve this ...

Encountering a 500 Error in an Angular 6 application on a .NET Core 2.1.1 framework when deployed

After upgrading my project from the old Visual Studio SPA Angular template to the latest version, including moving from Angular 5 to Angular 6 and webpack to angular-cli, I encountered an issue. While everything works fine in development, I'm facing a ...

Beginning external plugin in Angular 4 application

Is it possible to incorporate an external plugin into an Angular 4 application? I am looking to utilize the niceScroll plugin for a scrollable div, which is defined within a component. <div class="d-flex" id="scrollable"> <app-threads-list> ...

Is it necessary to include compiled JavaScript files in the Git repository?

Just starting out with TypeScript and curious about best practices according to the community. For production compilation, I currently use the webpack loader. However, during testing, I find myself needing to run tsc && ava. This results in the cr ...

Show array elements in Angular framework

I need help with displaying a list that contains three columns: menu, menuItem, and order. The desired display format is to show menu and menuItem ordered by order as follows: Menu 1 : order 200 Menu 2 : order 230 Menu 3 : order 250 Menu item 1 : order 2 ...

Unable to call an object that may be 'undefined': Utilizing a function with a return object that includes asynchronous functions as properties

I have a function exported in my adapter.ts file: import type { Adapter } from "@lib/core/adapters"; export default function MyAdapter (): Adapter { return { async createUser (user: User) { ... }, async findUserByEmail (email ...

Tips for passing a usestate via props using interfaces in TypeScript and react?

I am currently working on implementing a light/dark theme and I have 2 components involved in the process. The first component code snippet is shown below, where I have successfully implemented a boolean to toggle between styles: export interface Props ...

Angular2 component testing in progress

Currently, I am facing the challenge of creating unit tests for a Angular2 website. Specifically, I am unsure of how to approach testing components using traditional Unit testing methods. One such component that I would like to test is as follows: import ...

Inspect mat-checkbox during cypress testing

When attempting to use the cypress check() method to check a mat-checkbox element, I included the force parameter like so: Cypress.Commands.add('changeEmailLayoutCheckbox', () => cy .get(EMAIL_LAYOUT_CHECKBOX) .check({ force: true } ...

Error Detected: An unhandled error occurred, triggering a promise rejection: TypeError: The super expression must be either null or a function in Angular version 6

Upon deploying the application on AWS Elastic Beanstalk, an error has surfaced. While the build and deployment processes were successful, one module is giving a Super Expression error. The other modules are functioning correctly, and everything works fine ...

Adding the activateRoute class to Angular for enhanced functionality

My question pertains to a specific section in the book pro-Angular-6, where I encountered the following syntax: constructor(private model:Model,activatedRoute:ActivatedRoute) {} I am unsure about the following aspects: How can we use a class without i ...