The issue with IONIC/Angular lies in its inability to properly render the JSON data retrieved

I have recently started learning IONIC/Angular and Javascript, although I do have some background in other programming languages. The issue I'm currently facing is related to fetching JSON data from an external API (I've created the API with Strapi) and successfully receiving responses, but struggling to display them on Views

Below is the code snippet: enter image description here vowels.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
 
// Custom enum for search types (optional)
export enum SearchType {
  all = '',
  vowels = 'vowel',
  easy = 'easy',
  hard = 'hard',
  naglos = 'naglos',
  wyglos = 'wyglos',
  srodglos = 'srodglos'
}

// Custom enum for categories (optional)
export enum Categories {
  all = '',
  naglos = 'naglos',
  wyglos = 'wyglos',
  srodglos = 'srodglos'
}
 
@Injectable({
  providedIn: 'root'
})
export class VowelService {
  url = 'http://localhost:1337/vowels';
 
  constructor(private http: HttpClient) { }
 
  searchData(title: string): Observable<any> {
    return this.http.get(`${this.url}?name=${encodeURI(title)}`).pipe(
      map(results => results['Search'])
    );
  }

  searchVowel(type: Categories): Observable<any> {
  return this.http.get(`${this.url}?&categories.name=${type}`).pipe(
    map(results => results['Search'])
  );
}
 
  getDetails(id) {
    return this.http.get(`${this.url}?i=${id}&plot=full`);
  }
}

vowels.page.html

<ion-header>
  <ion-toolbar color="primary">
    <ion-title>Vowel Searcher</ion-title>
  </ion-toolbar>
</ion-header>
 
<ion-content>
 
  <ion-searchbar [(ngModel)]="searchTerm" (ionChange)="searchChanged($event)"></ion-searchbar>
 
  <ion-item>
    <ion-label>Select Type</ion-label>
    <ion-select [(ngModel)]="type" (ionChange)="searchChangedVowels($event)">
      <ion-select-option value="">All</ion-select-option>
      <ion-select-option value="naglos">Naglos</ion-select-option>
      <ion-select-option value="srodglos">Srodglos</ion-select-option>
      <ion-select-option value="wyglos">Wyglos</ion-select-option>
    </ion-select>
  </ion-item>
 
  <ion-list>
 
    <ion-item button *ngFor="let item of (results | async)" [routerLink]="['/', 'vowels', item.id]">

 
      <ion-label text-wrap>
        <h3>{{ item.id }}</h3>
        <h3>{{ item.name }}</h3>
      </ion-label>
 
 
    </ion-item>
 
  </ion-list>
 
</ion-content>

vowels.page.ts

import { VowelService, Categories } from './../../services/vowels.service';
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
 
@Component({
  selector: 'app-vowels',
  templateUrl: './vowels.page.html',
  styleUrls: ['./vowels.page.scss'],
})
export class VowelsPage implements OnInit {
 
  results: Observable<any>;
  searchTerm: string = '';
  type: Categories = Categories.all;
 
  constructor(private vowelService: VowelService) { }
 
  ngOnInit() { }
 
  searchChanged() {
    this.results = this.vowelService.searchData(this.searchTerm);
  }

  searchChangedVowels() {
    this.results = this.vowelService.searchVowel(this.type);
    
  }
}

Answer №1

If you are unable to display the data on your page because the map operator consumed the observable, try using it in your service file like this:

pipe(map(results => {
    return results["search"]
}))

This approach ensures that your function will return an Observable. Make sure to update the method in your vowels.page.ts file as shown below:

//Results can be of type object or any
results: any || yourDataModelType;  
this.vowelService.searchData(this.searchTerm).subscribe(results => {
    this.results = results;
})

By following this method, you create an Observable and consume it on your page when fetching data from the server.

Keep in mind that results will only be displayed when the observable returns consumable data.

Additionally, remember to unsubscribe from observables after use to prevent memory leaks. In Ionic/Angular, you can achieve this by implementing ngOnDestroy() as shown below:

//Declare a subscription variable in your page.ts   
sub: Subscription  

//Assign it within your function
this.sub = this.vowelService.searchData(this.searchTerm).subscribe(results => {
    this.results = results;  
})
 
//Implement OnDestroy cycle for the page
export class VowelsPage implements OnInit, OnDestroy

//Include ngOnDestroy and unsubscribe logic
ngOnDestroy(){  
    if(this.sub){sub.unsubscribe()}
}

To improve your understanding, explore the RxJs library and learn more about Observable types: https://www.learnrxjs.io/

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

What is the method for including a TabIndex property in a JSON file?

https://i.sstatic.net/ISi72.png I discussed the integration of HTML fields within a JSON file and highlighted how to utilize the TabIndex property effectively in JSON files. ...

Incorporating a Script into Your NextJS Project using Typescript

I've been trying to insert a script from GameChanger () and they provided me with this code: <!-- Place this div wherever you want the widget to be displayed --> <div id="gc-scoreboard-widget-umpl"></div> <!-- Insert th ...

Possible undefined object in React Redux

I'm encountering a Typescript issue where Redux object I am utilizing is potentially undefined, even though I have not specified its type as potentially being undefined or set it to be undefined anywhere in my code. /redux/globalSettings/actions.ts ...

Displaying random characters in place of Angular 6 font awesome icons

Recently, I started a new project with the angular cli and incorporated font-awesome 4.7.0. After that, I included it as a dependency in my angular.json file. "styles": [ "./node_modules/font-awesome/css/font-awesome.min.css", "./node ...

Master the art of iterating through an Object in TypeScript

I need help with looping through an Object in TypeScript. While the following examples work in JavaScript, I understand why they pose a problem in TypeScript. Unfortunately, I am struggling to find the correct approach to solve this issue. Am I approaching ...

What is the process for importing files with nested namespaces in TypeScript?

Currently, I am in the process of transitioning an established Node.js project into a fully TypeScript-based system. In the past, there was a static Sql class which contained sub-objects with MySQL helper functions. For instance, you could access functions ...

Resolving Circular Dependency Error in Angular Component due to Service Integration Testing

Delving into Angular Unit Testing has been a recent focus of mine as I've begun incorporating mock tests in one of my projects. However, I've hit a roadblock with an error popping up in one of my component tests: Error: NG0200: Circular dependen ...

Testing Angular - using observables that return varying values

I'm currently faced with the challenge of testing a component that subscribes to an observable in a service during its ngOnInit lifecycle hook. The component's behavior is expected to change based on the value received from the observable. To sim ...

Having trouble getting the Angular2 boilerplate to start with npm?

Just starting out with Angular2 and attempting to set up the environment using the boilerplate code found at https://github.com/mschwarzmueller/angular-2-beta-boilerplate. After successfully installing my dependencies with npm install, I encountered some ...

The issue with loading scripts in a ReactJS NextJS app is related to the inline condition not working

I'm having trouble with an inline condition for loading scripts. The condition seems to be working because the tag is displaying text, but when it comes to scripts, it doesn't work. How can I resolve this issue? const cookie = new Cookies().get ...

Troubleshooting ng module not found error when deploying Typescript + Angular app on Azure App Service using Azure DevOps pipeline

My Typescript and Angular application runs perfectly when tested locally. Now, I'm in the process of setting up a deployment pipeline using Azure DevOps to build and release it to an App Service running on Linux (Node.js web app). Although the pipel ...

The reloading feature in Angular components is not functioning as intended

I am looking for a way to refresh the component without having to refresh the entire page. Below is the code snippet that I have been using: import { Component, VERSION, OnInit } from '@angular/core'; import { Router, ActivatedRoute } from &apos ...

How to check all checkboxes in Angular using ngFor and ngIf?

Is there a way to select all checkboxes in an Angular form that uses ngFor and ngIf? I want to activate all checkboxes for the months when I click on "Select All". The list of months is stored in an array. Click here to see the HTML representation of the ...

Angular Reactive Forms: Implementing Error Display and Red Border Styling

Recently, I've started diving into Angular Reactive Forms and I'm quite impressed by the async validator feature for tasks that involve checking data against a database. The separation of validation rules from the GUI is also very appealing to me ...

Which grid systems work well with Angular4, particularly for organizing and refining table data?

Experimented with using ag-grid as it seemed to be the most suitable option. In my package.json, I have the following dependencies: "ag-grid": "^18.1.2", "ag-grid-angular": "^14.0.0", "ag-grid-community": ...

Error in TypeScript when using keyof instead of literal in type pattern.Beware of TypeScript error when not

let c = { [X in keyof { "foo" }]: { foo: "bar" } extends { X } ? true : false }["foo"]; let d = { foo: "bar" } extends { "foo" } ? true : false; c and d should both return true, but surprisingly, c is eval ...

What is the best way to set an array as the value for a state variable?

Looking at my function, I have the following situation: execute(e) { let { items } = this.context; let array: number[] = []; for (var i = 0; i < 2; i++) array = [...array, i]; this.setState( { items: array, } ) ...

The path referenced in typings is incorrect

I am currently facing an issue with my Typescript library that I am trying to publish on npmjs. It seems like the types file is not being exported correctly. The library has a simple method in the src/index.ts file and typings from src/typings/index.d.ts. ...

Getting the latest version number of an app from the Google Play Store for an IONIC project

Is there a way to determine if the app needs to be updated from the playstore? I want to display a message prompting users to update their app. Any suggestions on how to implement this feature? ...

Bringing together a collection of objects connected by shared array elements

Given the types defined as: type A = { commonKey: { a: string }[] }; type B = { commonKey: { b: number }[] }; Is it possible to create the type below without explicitly specifying commonKey? type C = { commonKey: { a: string, b: number }[] } My initial a ...