Utilize Angular 5 to create a Data Service for extracting JSON data from MongoDB

Seeking to incorporate a data service for reading json data from mongoDB, I initially implemented the function directly within the ngOnInit() of my component successfully. However, when attempting to create a separate data service, I encountered difficulties in getting the json data into my component.

intro-animation.component.ts:

export class IntroAnimationComponent implements OnInit {
  keywords: string[];
  ...
}

constructor(
  private _http: HttpClient) {
  ...
}

ngOnInit() {
  this._http.get('./api/keywords').subscribe(res => {
    this.keywords = res['data'];
  });
}

While the initial implementation works well, I now aim to develop a data service class that can be utilized by other components to access various tables in my database:

data.service.ts

import { Injectable } from '@angular/core';
import 'rxjs/add/operator/map';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class DataService {
  results: string[];

  constructor(private _http: HttpClient) { }
    getKeywords(): string[] {
      this.getKeywordsObservable().subscribe(res => {
      this.results = res['data'];
    });
    return this.results;
  }

  getKeywordsObservable(): Observable<any> {
    return this._http.get("./api/keywords")
  }
}

I have registered the service in my app.module, but I am uncertain about how to transfer the data from the service to my component.

intro-animation.component.html

<div class="keywords-container" *ngFor="let keyword of keywords">
  <div class="keyword" [ngStyle]="setKeywordFontParams()">
    {{ keyword.name }}
  </div>
</div>

mongoDB json data

{
"status": 200,
"data": [
    {
        "_id": "5a60740d94d06e102e8c2475",
        "name": "Passion"
    },
    {
        "_id": "5a60745be4b93b2c36f6a891",
        "name": "Grandeur"
    },
    {
        "_id": "5a607461e4b93b2c36f6a892",
        "name": "Prestige"
    }
],
"message": null
}

Being relatively new to Angular, any guidance on how to proceed would be greatly appreciated.

Answer №1

When your dataService's getKeywords() method calls http.get, it is an async operation. Therefore, if you try to return this.results;, it will still be undefined and return nothing.

A better approach would be to return an observable directly from the data.service.ts file. For example:

 getKeywordsObservable(): Observable<any> {
    return this._http.get("./api/keywords")
  }

Then, subscribe to this observable inside the intro-animation.component. Like this:

ngOnInit() {
      this._dataService.getKeywordsObservable().subscribe(res => {
        this.keywords = res['data'];
      });
    }

Answer №2

animation-introduction.component.ts:

import {DataService} from "<service location>" 

    export class AnimationIntroductionComponent implements OnInit {
      words: string[];

    constructor(
      private _service: DataService) {
      ...
    }

    ngOnInit() {
      this._service.getWords().subscribe(res => {
        this.words = res;
      });
    }

word.service.ts

import { Injectable } from '@angular/core';
import 'rxjs/add/operator/map';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class WordService {

  constructor(private _http: HttpClient) { }


  getWords(): Observable<any> {
    return this._http.get("./api/words")
  }
}

We hope this information is beneficial.

Answer №3

Here's an example of how you can achieve this:

import { Injectable } from '@angular/core';
import 'rxjs/add/operator/map';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class DataService {

  constructor(private _http: HttpClient) { }

  public fetchKeywords(): any {
    return this._http.get('./api/keywords').map(response => {
      return response['data'];
    });
  }

}

To use this service in your component, simply inject it and call dataService.fetchKeywords()

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

Troubleshooting Async Function compatibility between Express and NestJs

Initially, I set up a small express server to handle report generation and file writing tasks. var ssrs = require('mssql-ssrs'); var fs = require('fs'); const express = require('express') const app = express() const port = 30 ...

Why are the description and summary being combined in Jira API when creating a new issue?

Currently, I am in the process of developing a Powershell script that focuses on monitoring disk space and generating Jira issues based on the available disk space. One challenge I am facing is separating the summary from the description. They seem to be ...

What is the best way to convert an array of JSON objects into a two-dimensional array in Java using GSON?

I have a JSON string that looks like this: [{ "id": 3, "city": "Ilmenau", "floor": null, "housenumber": "35", "streetname": "Blumenstraße", "zip": "98693" }, { "id": 4, "city": "Berlin", "floor": null, "housenumber ...

What is the process for sending an array to a Jenkins parameterized job using the remote access API?

I need assistance in calling a Jenkins parameterized job using the curl command. I am referring to the Jenkins Remote API documentation. The job involves an Active choice parameter plugin with one parameter being an Active choice reactive parameter. Atta ...

Implement a for loop within the function responsible for creating a collection in Firebase

I am currently developing a food application using Ionic (4) /Angular that can manage multiple stores and integrates Firebase. However, I have encountered a problem. When creating a new order, I use the following code: add(stores: Array<CartStore>, ...

Neglecting the error message for type assignment in the Typescript compiler

Presented here is a scenario I am facing: const customer = new Customer(); let customerViewModel = new CustomerLayoutViewModel(); customerViewModel = customer; Despite both Customer and CustomerLayoutViewModel being identical at the moment, there is no ...

Bringing in TypeScript declarations for the compiled JavaScript librarybundle

I have a custom library written in TypeScript with multiple files and an index.ts file that handles all the exports. To consolidate the library, I used webpack to compile it into a single index.js file but now I'm facing challenges importing it with ...

In Doctrine Mongo, when a child entity is the owning side, cascading removal can be

My current setup involves a parent/child relationship where one parent can have many children: /** * @ODM\Document */ class Parent { // ... /** * @var \Doctrine\Common\Collections\ArrayCollection * @ODM\R ...

Retrieving information from a function beyond the scope of Mongoose

I am currently facing an issue with my function in which I need to return the Mongoose query data so that I can use it. However, I am only able to access the sum within the .exec function. How can I manage to retrieve the sum value outside of this functi ...

Resizing the elements within an iframe: Troubleshooting problems with embedding Bandcamp players

My goal is to embed a Bandcamp music player on my WordPress blog page, but I'm facing a challenge. The maximum width of the current player is 700px and I need it to be 900px. After consulting with someone at Bandcamp, they directed me to the old versi ...

Ways to personalize the interface following the selection of an item from a dropdown menu

Currently, I am using Vue.js and Typescript for my project work. I have a requirement to customize the interface by making adjustments based on the selected item from a drop-down list. <b-form-select id="input-topic" ...

Webpack does not support d3-tip in its current configuration

I'm having some trouble getting d3-tip to work with webpack while using TypeScript. Whenever I try to trigger mouseover events, I get an error saying "Uncaught TypeError: Cannot read property 'target' of null". This issue arises because th ...

Angular 6 Modal Window

Currently, I am working on implementing a popup window in Angular 6. I am following the example provided in this link: https://stackblitz.com/angular/brrobnxnooox?file=app%2Fmodal-basic.html Here is the HTML code: <div class="form-group"> <ng- ...

What are some effective measures to defend against a gzip bomb attack on a service

I have a file named test.gzip which contains JSON data. {"events": [ {"uuid":"56c1718c-8eb3-11e9-8157-e4b97a2c93d3", "timestamp":"2019-06-14 14:47:31 +0000", "number":732, "user": {"full_name":"0"*1024*1024*1024}}]} The full_name field in the JSON data c ...

Storing JSON data in a Postgres database using Elixir and Phoenix

I have searched extensively for solutions to this problem. Utilizing the phx.gen generator, I created some CRUD functionalities. My goal is to establish repositories in my database and store GitHub activity within them. Here is my migration: def change ...

The issue of process.server being undefined in Nuxt.js modules is causing compatibility problems

I've been troubleshooting an issue with a Nuxt.js module that should add a plugin only if process.server is true, but for some reason it's not working as expected. I attempted to debug the problem by logging process.server using a typescript modu ...

Module 'next-intl/client' cannot be located

When I run npm test, I encounter the following error: 'next-intl/client' module not found jest.mock( | ^ 22 | 'next-intl/client', 23 | (): Record<string, unknown> => ({ 24 | usePathname: ...

Step-by-step guide on uploading an image file using Nextjs

I am attempting to achieve the following: Upload an image file to a Next.js application Process it using cjwbw/real-esrgan:d0ee3d708c9b911f122a4ad90046c5d26a0293b99476d697f6bb7f2e251ce2d4 Retrieve the enhanced version of the image Is there anyone who can ...

Console unable to display extensive JSON data

Using node.js, I have created a module that retrieves data from a SQL server database in JSON format. Below is the code: b.js var mssql = require('mssql'); var config = { user: 'sa', password: 'scott', server: & ...

Looking for a way to navigate through nested JSON data within a JSX component in a React Native application

When I attempt to display the server response, I am encountering an issue in my code related to accessing nested JSON data. Below is the structure of the JSON: Updated: { "child": [], "courses": [{ "data": { "name": "Student ...