Tips for transferring data from a file located outside an Angular library to files within the Angular library

In the repository below, you will find a library named posts-lib. This library contains a file named posts.services.ts which is responsible for making http calls and retrieving a list of posts to display on the screen. Additionally, there is a component named title.component.ts which depends on posts.services.ts to display content on the screen.

Everything is functioning as expected. However, if there is a need to relocate the posts.service.ts folder from the library and place it inside the app, how can data be transferred from a file outside the library to the title.component.ts file which depends on it?

title.component.html

    <h1>Testing titles api call</h1>

    <ul>
      <li *ngFor="let item of data">{{item.title}}</li>
    </ul>

title.component.ts

    import { Component, OnInit } from '@angular/core';
    import { PostsService } from '../posts.service';
    
    
    @Component({
      selector: 'lib-tilte',
      templateUrl: './tilte.component.html',
      styleUrls: ['./tilte.component.css']
    })
    export class TilteComponent implements OnInit {
    
      data: any;
    
      constructor(private postData: PostsService) { }
    
      ngOnInit() {
        this.postData.getPosts().subscribe((result) => {
          console.warn("result",result);
          this.data = result;
        })
      }
    
    }

posts-lib.component.ts

    import { Component, OnInit } from '@angular/core';
    
    @Component({
      selector: 'lib-posts-lib',
      template: `
        <p>
          posts-lib works!
        </p>
      `,
      styles: [
      ]
    })
    export class PostsLibComponent implements OnInit {
    
      constructor() { }
    
      ngOnInit(): void {
      }
    
    }

posts-lib.module.ts

    import { NgModule } from '@angular/core';
    import { PostsLibComponent } from './posts-lib.component';
    import { TilteComponent } from './tilte/tilte.component';
    import { HttpClientModule } from "@angular/common/http";
    import { CommonModule } from '@angular/common'
    
    
    
    @NgModule({
      declarations: [
        PostsLibComponent,
        TilteComponent
      ],
      imports: [
        HttpClientModule,
        CommonModule
      ],
      exports: [
        PostsLibComponent,
        TilteComponent
      ]
    })
    export class PostsLibModule { }

posts.service.ts

    import { Injectable } from '@angular/core';
    import { HttpClient } from "@angular/common/http";
    
    @Injectable({
      providedIn: 'root'
    })
    export class PostsService {
    
      url = "https://jsonplaceholder.typicode.com/posts";
    
      constructor(private http: HttpClient) { }
    
      getPosts() {
        return this.http.get(this.url);
      }
    }

public-api.ts

    export * from './lib/tilte/tilte.component';
    export * from './lib/posts-lib.service';
    export * from './lib/posts-lib.component';
    export * from './lib/posts-lib.module';
    export * from './lib/posts.service';

Answer №1

Despite the criticisms raised by commenters - all of which are valid - it appears that the goal is to eliminate the reliance on the service.

Well, maybe not entirely.

Choices, choices!

  1. Eliminate using the service

Simply reorient the component so that it receives its data instead of fetching it on its own. In other words, use @Input.

  1. Still utilizing @Input, but this time, input the service itself rather than just the values.

So either:

@Input() public data: any;

or

@Input() public set service(value: PostsService) {
    this.postsService = value;
    this.getData();
}

private getData(): void {
    this.postsService.getPosts().subscribe(...);
}

Regardless of the approach taken to decouple the service and component and no longer treat them as interconnected entities within a system, you must extract the component and provide it with information using @Input.

Whether this involves merely passing data from a wrapper service or handing over the service itself from its new location, the component still needs to receive it.

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

Create a new button dynamically within an HTML table row using pure JavaScript programming techniques

Currently, I am retrieving JSON data from an API and then displaying this data in an HTML table using plain JavaScript. My goal is to dynamically add a button at the end of each row for additional functionality, but so far, I have been unable to figure out ...

What are the most effective applications for utilizing an Observable Data Service?

Within my application setup, I have integrated a data service at the core level. The majority of functions within my app involve actions taken on the data model, to which components react. My goal is for components to be able to subscribe to the data ser ...

Error message: "The property is not found within the specified type when using the OR operator with

Within my Angular component, I am faced with a challenge involving an Input that can be one of two types. @Input() profile: UserProfileDetails | BusinessProfileDetails; The structure of the profile template is straightforward and I want to avoid duplicati ...

Tips for preloading a script in nextjs

I'm having trouble incorporating a script into my website. The issue is that the script doesn't load properly the first time the page loads, but after a few refreshes, it works and the responsible iFrame shows up. I've attempted several di ...

Guide on incorporating a YouTube iframe in React with Typescript

It appears that Typescript is posing some challenges for me in this scenario. Here's the code snippet I am trying to include: <iframe width="560" height="315" src="https://www.youtube.com/embed/BLAH?showinfo=0" frameBorder="0" ...

Encountering the error "No exported member ɵɵFactoryDef in Angular 8 when trying to access /node_modules/@angular

Encountering the following error when attempting to run the ng serve command and also in ng build --prod. ERROR in ../node_modules/mat-file-upload/lib/mat-file-upload.component.d.ts:21:21 - error TS2694: Namespace '"/root/storeproj/node_modules/@angu ...

Exploring the features of Typescript involving async/await, Promise, and the use of function

I am currently working on a nodeJS-Express-Typescript project where I need to implement native promises with async/await and also provide default values for functions. Here is a simple example of what I am trying to achieve: sleep(ms: number) { return ...

The JSON data in ajax is not formatted correctly

Hey everyone, I'm facing a really frustrating error. I have a JSON formatted array that I'm passing from a PHP script to JavaScript through AJAX. Despite validating the JSON output, I keep encountering an error at the jQuery.parseJSON() step, whi ...

Tips for switching the status of each item as I navigate the page with the tab key

I am facing an issue with my list of items that have hidden content appearing on hover. I want to achieve the same functionality while tabbing through my page, but currently, all hidden content appears at once. Check out a live example of my code here jQ ...

Tips for accessing a specific value within an array of objects using a key

Is there a way to retrieve the value in an object array based on a key that is present within the same array? The structure of the object array is as follows: const objectArray = [ {key: "1", value: "12321"}, {key: "2", value: "asdfas"} ] For ex ...

Building a React Redux project template using Visual Studio 2019 and tackling some JavaScript challenges

Seeking clarification on a JavaScript + TypeScript code snippet from the React Redux Visual Studio template. The specific class requiring explanation can be found here: https://github.com/dotnet/aspnetcore/blob/master/src/ProjectTemplates/Web.Spa.ProjectT ...

Sharing a Detailed Mongoose Schema

Hey there! So, I've been working on this Mongoose Schema and there seems to be something off about it. The main area of concern is the "region" part. const mongoose = require('mongoose'); const destination = new mongoose.Schema({ ...

Issue with Bcrypt comparison resulting in constant false output

Attempting to implement password verification using bcryptjs, const bcrypt = require('bcryptjs'); login(post){ this.uid = post.uid; this.pin = post.pin; this.getUser(this.uid); if(this.checkUser != undefined ...

Can images be sent to an Express API using SvelteKit's `on:change` event handler in combination with Form Actions?

I have a SvelteKit application that interacts with an Express API to store user data. Within my app, there is a form containing an input file field where users can upload images to be saved on the Express server using Form Actions. The issue I am facing ...

Getting a "SyntaxError: Unexpected end of input" error while using jQuery ajax with valid JSON

The PHP response in JSON format shows: {"success":0,"message":"Error: No entityId passed!"} However, my JavaScript code throws an error "SyntaxError: Unexpected end of input". PHP: ... //check if an image id was passed for removal in the POST ...

Launching a modal in a new browser window with the help of JavaScript or PHP

I need to implement a feature where clicking a link opens a modal in a new tab and redirects the current page to a different link, similar to how retailmenot handles coupons. Here is the code snippet I am currently working with: <div onClick="myFunctio ...

The ng-show directive seems to be malfunctioning when used with UnderscoreJS's _.isNull function, but it functions properly when comparing

When using an ng-show directive on an element, I noticed that the UnderscoreJS helper function _.isNull behaves differently than the standard === operator. For example, when checking if newJobWorkPercentage is null: <div class="form-group" ng-show="ne ...

Encountered difficulties sending JSON data to a REST endpoint using Node.js

Is there a way to bulk insert JSON data into MongoDB using Mongoose? I am aware of the insertMany method, but I'm encountering difficulties with extracting the correct req.body. Below is an image of my setup in Postman. https://i.sstatic.net/xFznd.pn ...

Performing a bulk create operation with Sequelize using an array

I am facing a task where I have an array of items that need to be created in the database. My approach is to check each insertion for success. If successful, I will add the item with a flag indicating success as true in a new array (results) in JSON forma ...

Numerous pop-up windows displaying a variety of distinct content in each one

While working on a website, I came across a helpful jQuery pop-up function that I found on Stack Overflow. The original post can be found here. I am trying to customize each pop-up box so they contain different content from the .pop1 and .pop2 divs (parag ...