How can I leverage the data fetched from API in Angular 13?

Just dipping my toes into the world of Angular by creating a quiz app to gain some hands-on experience. Successfully receiving a random set of questions from the API, but now facing the challenge of iterating over this array to implement the gameplay. The aim is to display one question at a time and update the score upon selecting the correct answer.

Not expecting a complete solution here. The resources I've consulted so far cater to simpler applications, leaving me unsure about their applicability in my scenario. Any high-level overview or a couple of next steps would be greatly appreciated.

The API call is made in the 'parent' component responsible for rendering the question, which in turn serves as the parent for displaying the answers.

Coming from a React background, my instinct is to manage state where the API request is issued and pass it down through props for rendering. Uncertain how this aligns with Angular's approach.

Sharing my api.service.ts file:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Injectable({
  providedIn: 'root',
})

export class apiService {
  constructor(private http: HttpClient) {}
  apiURL = 'http://localhost:8080';

  httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json',
    }),
  };

  getQuiz(category: any) {
    console.log('bacon');
    
    return this.http.get(this.apiURL + '/quiz/' + category).subscribe((res) => {
      console.log(res);
    })
  }
}

Confirms that console.log(res) is functional.

Next, my game-window.component.ts file:

import { Component, OnInit } from '@angular/core';
import { apiService } from '../shared/services/api.service';

@Component({
  selector: 'game-window',
  templateUrl: './game-window.component.html',
  styleUrls: ['./game-window.component.css'],
})


export class GameWindowComponent implements OnInit {
  constructor(private _apiService: apiService ) {
    
  }
  
  ngOnInit() {
    this._apiService.getQuiz(window.location.pathname.split('/')[1]);
  }
}

Fairly new to TypeScript overall, so uncertain about the syntax required to persist the expression within ngOnInit()

Any guidance, even a basic step-by-step outline in plain language, would be incredibly helpful. Thanks!

Answer №1

For your situation, it would be more beneficial to return the Observable instead of subscribing to it within the apiService. You can then subscribe to it in your component in order to await the response.

The type of response will be defined by YourResponseType, and the httpClient is responsible for mapping and returning the object.

// API SERVICE
getQuiz(category: any): Observable<YourResponseType> {
console.log('bacon');
return this.http.get<YourResponseType>(this.apiURL + '/quiz/' + category);
}

// COMPONENT
ngOnInit() {
    this._apiService.getQuiz(window.location.pathname.split('/')[1])
.subscribe((response: YourResponseType) => {
   // Now you can assign the response to your component properties

});
    }

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

Managing quick mouse movements while resizing an element during a mousemove event

I'm seeking to implement a resizable modal that only adjusts its height. I've written some code, but when I attempt to extend it downwards quickly, it exceeds the element boundaries without any effect. I've come across codes that work proper ...

Display fresh information that has been fetched via an HTTP request in Angular

Recently, I encountered an issue where data from a nested array in a data response was not displaying properly in my component's view. Despite successfully pushing the data into the object programmatically and confirming that the for loop added the it ...

Creating Instances of Parameterized Types

Consider the following scenario: class Datum {} An error message (error TS2304: Cannot find name 'T') is encountered when attempting the following: class Data<T extends Datum> { datum: T constructor() { this.datum = new ...

Is there a way to update the data on a view in Angular 9 without the need to manually refresh the page?

Currently, I am storing information in the SessionStorage and attempting to display it in my view. However, there seems to be a timing issue where the HTML rendering happens faster than the asynchronous storage saving process. To better illustrate this com ...

How can you transfer array elements to a new array using JavaScript?

I have a task to transform the fields of an array received from one server so that they can be understood by another server for upload. My approach involves first retrieving and displaying the original field names from the initial server's array to al ...

The installation of Node on Ubuntu 18.04 encountered an error

Could someone assist me with this problem? I initially had node installed, then uninstalled it using the rm -rf command following online suggestions. Now I am trying to reinstall it using nvm install node However, I'm encountering the following error ...

The comparison between ng-content and router-outlet in Angular 2

Can someone help me decide on the best approach for structuring my components? i. The first approach involves using ng-content in the parent component and then creating child components enclosed within the parent's selector. For example, creating a ...

The success method in the observable is failing to trigger

Could someone explain why the () success method is not triggering? It seems to be working fine when using forkjoin(). Shouldn't the success method fire every time, similar to a final method in a try-catch block? Note: Inline comments should also be c ...

(TS 2556) I'm puzzled as to why a type error is being thrown for a spread argument that was clearly defined and passed as a rest parameter

function debouncePromise<TParams extends Array<unknown>, TRes>( fn: (a: TParams) => Promise<TRes>, time: number, ) { let timerId: ReturnType<typeof setTimeout> | undefined = undefined; return function debounced(...args: TP ...

Determine the generic type of the parent class based on the constructor of the child class

Below is a code snippet illustrating the issue at hand: class Parent<T = unknown> { constructor(private prop: T) {} getProp(): T { return this.prop; } } class Child extends Parent { constructor() { super({ ...

Module 'rxjs/internal/Observable' not found

When attempting to utilize the JwtHelperService module in my service, I encountered the following error: ERROR in node_modules/@auth0/angular-jwt/src/jwt.interceptor.d.ts(3,28): error TS2307: Cannot find module 'rxjs/internal/Observable'. In my ...

Unable to access property '_lastPathIndex' of an undefined value

In my component spec, I am simulating the Activated Route like this: class ActivatedRouteMock { public paramMap = of(convertToParamMap({ level: 'customer', id: '12345', })); } I have also added this class in the providers ...

Troubleshooting Issue with Angular Library: Live Reload Feature Not Functioning

In setting up my Angular workspace, I have 3 libraries and one application (with more to be added in the future). This is how the TypeScript paths are configured: "paths": { "@lib/a/*": [ "projects/libs/a/*", ...

Tips for preloading a TypeScript class using the -r option of ts-node

Imagine you have a file called lib.ts that contains the following code: export class A {} console.log('script loaded'); Now, if you launch the ts-node REPL using the command: npx ts-node -r ./lib.ts, you will see that it outputs "script loaded," ...

Accessing props in setup function in Vue 3

I am encountering issues when trying to access the props value (an array) in my composition API setup. The component I have is called DropDown, and I am passing it an array of objects. Here's what I need to achieve: export default { emits: ['up ...

What is the best way to access the values associated with the keys in an array of objects?

I have an array of objects that has the following structure: import icon1 from '!!raw-loader!../../../icon1.svg'; import icon2 from '!!raw-loader!../../../icon2.svg'; import icon3 from '!!raw-loader!../../../icon3.svg'; import ...

Establish an enumeration using universally recognized identifiers

I have a JavaScript function that requires a numerical input, as well as some predefined constants at the top level: var FOO = 1; var BAR = 2; The function should only be called using one of these constants. To ensure type safety in TypeScript, I am att ...

Guide on transforming observable<User> to Observable<boolean> in Angular 4

As a newcomer in Angular and Mean Stack, I need help implementing the canActivate() method to restrict admin routes. In my service file, the checkAdmin method returns an observable of type "User", but the canActivate method's return type is an observa ...

ControlValueAccessor can automatically detect when the required property is enabled on a reactive form

Is there a way to detect within a custom control, that implements ControlValueAccessor and is exclusively utilized with reactive forms, when the required validator has been added or removed? I am looking for an alternative solution instead of creating an ...

What's the Best Way to Add a Custom Flag to the `nx angular serve` Command Without Triggering an Error?

When running the nx angular serve command, I want to add my custom flag (-t example). But when I try this, I get an error message from nx that says: 't' is not found in schema To address this issue, I plan to capture this flag in proxy.mjs an ...