Attempting to troubleshoot an issue with asynchronous operations that are returning an observable

When I console log my .then() function, it only gives me an observable. How can I retrieve the actual data that is being returned?

I've been struggling to solve my async/await issue and haven't been able to figure out a solution. Currently, my page loads first and then the data comes in, leading to an error being thrown in the console. The data eventually arrives, but not before the error occurs.

This is the component ts code snippet:

async getGames() {
    await this.games.getAllGames(this.currentPage).then(game => {
      this.gamesArray = game;
    });
}

This is from my service file:

async getAllGames(page) {
    console.log('11111111111111');
    const queryParams = `?page=${page}`;
    return await this.http.get(this.url + queryParams);
}

This is my HTML:

<div class="col-lg-9 float-right">
    <div class="row">
        <div class="col-lg-6 card-background" *ngFor="let game of gamesArray.games">
            <div class="card-surround shadow-sm">
                <div>
                    <h2>{{game.homeTeam.teamName}}</h2>
                    <h2>{{game.awayTeam.teamName}}</h2>
                    <canvas id="{{game.id}}"></canvas>
                    <hr>
                    <p>{{game.gameTime}}</p>
                </div>
            </div>
        </div>
    </div>
    <ngb-pagination class="d-flex justify-content-end" 
        size="sm" 
        [collectionSize]="gamesArray.games.length" 
        [(page)]="currentPage"
        [maxSize]="5" 
        [pageSize]='6'                  
        [rotate]="true" 
        [ellipses]="false"
        [boundaryLinks]="true"
        (pageChange)='onPageChange($event)'>
    </ngb-pagination>
</div>

The issue is that the 'game' variable in the .then() function is returning an observable instead of the expected data from the server/database.

Answer №1

Completely agree with @alexortizl's suggestion - simply add toPromise() to the result of getAllGames() and it should work perfectly.

async getAllGames(page) {
      console.log('11111111111111');
      const queryParams = `?page=${page}`;
      return await this.http.get(this.url + queryParams).toPromise(); // <--- like this
    }

In addition, you also have the option to directly use the observable returned by this.http.get(...). Just remember to utilize subscribe instead of then.

Check out this example on StackBlitz for a visual representation of how the code would appear. https://stackblitz.com/edit/angular-j7bh6e?file=src%2Fapp%2Fgame.service.ts

Answer №2

One issue to address is that when using angular, the http.get() method returns an Observable. So, within your getAllGames() function, if you have:

return await this.http.get(this.url + queryParams)
;

You are actually returning an Observable rather than a Promise. It should be corrected to something like this:

return await this.http.get(this.url + queryParams).toPromise()
;

Furthermore, in the getGames() function, if you are utilizing await, there is no need to use the promise then() method. Instead, it should be structured like so:

async getGames() {    
    const game = await this.games.getAllGames(this.currentPage);
    this.gamesArray = game;
}

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

Transform Text into Numeric Value/Date or Null if Text is Invalid

Consider the TypeScript interface below: export interface Model { numberValue: number; dateValue: Date; } I have initialized instances of this interface by setting the properties to empty strings: let model1: Model = { numberValue: +'', ...

There seems to be a discrepancy with the absence of app-routing.module.ts and app.module.ts files within the

I've started a new ionic project by running this command : ionic start During the setup process, I selected Angular framework and chose to create a blank project. However, upon project creation, I noticed that the app-routing.module.ts and app.modul ...

Tips for testing the RXJS pipe method using Jasmine

I need assistance with covering the pipe function of RXJS in Angular/Jasmine. An error is popping up: TypeError: this.element.children.pipe is not a function Here's the snippet of code causing the issue: ngOnInit() { this.element.children.pipe( ...

Make the download window appear automatically when downloading a file

How can I use JavaScript/TypeScript to prompt the browser to open the download window? My goal is to give users the ability to rename the file and select the download folder, as most downloads are saved directly in the default location. This is how I curr ...

Is it possible for me to reinstall npm in an Angular project as a solution?

I recently started working on an Angular 9 project and installed various libraries. However, I encountered some issues with ngx-gallery and Renderer2 which led me to make edits in files like core.d.ts within the node_module/angular/core directory. As a new ...

What is the best way to create an "ArraySimilar" class using TypeScript?

Can someone guide me on creating an ArrayLike class in TypeScript? Edit: Got the solution from @jcalz, it's working perfectly for me. class CustomArray<T> implements ArrayLike<T> { length: number [index: number]: T } ...

Is there a way to signal an error within an Observable function that can handle multiple scenarios depending on the specific page being viewed in an Angular application?

Currently, I have a function called getElementList() which returns Observable<Element[]>. The goal is to handle different scenarios based on the user's current page - two cases for two specific pages and one error case. However, I am struggling ...

Combining two rows into a single cell using AG-GRID

Currently, I am utilizing AG-GRID for angular in my code. Within this grid, I have two columns available - Account.Name and Account.Surname. My goal is to display the values from these two columns within a single cell. To achieve this, I attempted the meth ...

How to Override Global CSS in a Freshly Created Angular Component

My CSS skills are a bit rusty and I need some assistance with a project I'm working on. The project includes multiple global CSS files that have properties defined for different tags, such as .btn. However, these global CSS files are causing conflicts ...

Creating a specialized feature for saving form data with React Admin

Within my react-admin application, I am faced with a scenario where I have a list of items accompanied by two separate buttons: "Create using email" and simply "Create". The "create" button utilizes the functionality provided by the data provider, which is ...

shared interfaces in a complete javascript application

In the past, I have typically used different languages for front-end and back-end development. But now, I want to explore the benefits of using JavaScript/TypeScript on both sides so that I can have key data models defined in one central location for both ...

Challenges with Mongo output in the MEAN stack

Recently delving into the MEAN stack Currently following a guide at All necessary installations have been completed. Upon executing mongod, the following output is generated: 2017-12-30T11:38:12.746+0000 I FTDC [initandlisten] Initializing full- ...

mat-auto complete display names but submit values

An option select that utilizes auto-complete to display a list of options. Each option is represented by an object. My goal is to display the name of each option while sending its ID. The code currently shows the ID once an option is selected, but I want i ...

Transform event binding using PrimeNG Elements and Angular

My challenge lies in dynamically binding change events within the PrimeNG TreeTable by defining functions on my columns. I've noticed that attempting to bind the change event dynamically with my columns doesn't seem to work properly inside the Tr ...

How to dynamically customize styling on md-tab in Angular2-material?

Styling material design components can be challenging, especially when trying to dynamically set styles on an md-tab based on its active or archived state. I'm looking to make the tab header text italic and change its color to indicate whether it is a ...

Customizing output paths for script files in angular.json with Angular

Is there a way to set up the configuration in angular.json so that script files are output as shown in the directory tree below? Note: The file aaa.js has been renamed from main.js /assets/js/aaa.js ...

How to use TypeScript to filter an array based on the values of another array

Suppose I have two arrays. The first one looks like this: names: [{ value: 'recordedData', desc: 'Data' } { value: 'recordedNumbers', desc: 'numbers' } { value: 'recordedNames', desc: 'name ...

Omit functions from category

This question reminds me of another question I came across, but it's not quite the same and I'm still struggling to figure it out. Basically, I need to duplicate a data structure but remove all the methods from it. interface XYZ { x: number; ...

What is the best way to display individual records from a Web API on the user interface?

Just a heads up: I'm unable to utilize pagination (skip, take) due to the data being sourced from multiple tables. For more information, you can refer to the Report model. I attempted to retrieve the data individually on the UI through WebAPI. The ...

Issue: Module XXX not found (TypeScript aliases)

Encountered a perplexing issue that I can't seem to solve. I am in the process of creating an NPM package to serve as a backend API for another project. Utilizing TypeScript and Node.js for development. My objective is to modify my import statements ...