Dependencies between Angular (Ionic) Services and Models

Someone advised me that for an Ionic project, it is necessary to use a service for each object.

Here are my models:

export class Document{
    idDocument: number;
    listFields: Fields[];
}
export class Field{
    idParentDocument: number;
    idLinkToOtherDocument: Document;
}

And here are my services :

export class DocumentService{
    constructor(private http: httpService, private fieldService: FieldService){}

    getFields(document: Document){
       this.fieldService.getFieldsByDocumentId(document.id);
       // Retrieve the fields of the document
    }

    getDocument(id: number){
       // Retrieve the document and its fields
    }
}

export class FieldsService{
    constructor(private http: httpService, private documentService: DocumentService){}

    getParentDocument(field: Field){
       // Retrieve the parent document of the field
    }

    getLinkedDocument(field: Field){
       // Retrieve the linked document of the field
    }

    getFieldsByDocumentId(id: number){
       // Retrieve the fields by document Id
    }
}

Sometimes I encounter situations where I need to access objects from other objects, as shown in my example. However, this often leads to circular dependencies. In Java, you could simply call the functions, but in Angular, it's not straightforward. I am contemplating reverting to my previous design pattern where all functions were within objects instead of services, requiring me to pass all other services (database service, server service...). This would result in a significant refactoring effort for something I was told was bad design. Personally, I find it more convenient with object services as I have easy access to all services without passing them as arguments.

What do you think I should do?

Answer №1

Personally, I choose not to pass services as arguments or inject them into each other. It is more cost-effective to refactor them now rather than later when trying to maintain the code or fix bugs. Let's break it down a bit:

 getFields(document: Document){ // only need documentId, not entire document object
       this.fieldService.getFieldsByDocumentId(document.id); 

    } 
//the function name implies it returns fields using the field service; there's no need to redefine it in the document service.
//Anyone wanting to get fields of a document should use the fields service! 



export class FieldsService{
    constructor(private http: httpService, private documentService: DocumentService){}

    getParentDocument(field: Field){
      // returns document and belongs in DocumentsService.
     //probably making an API call here; do you need the entire field object? NO
    }

    getLinkedDocument(field: Field){
       // same as above
    }

    getFieldsByDocumentId(id: number){
       //it's fine.
    }
}

If your objects persist throughout your application, for instance, when you don't need an API call to retrieve a document's fields, I recommend something like NgRx, which centralizes your application's state.

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 could be causing the error I encounter when attempting to send JSON in a GET request?

Currently, I am utilizing Angular 10 in my project. I am attempting to send an object in a GET request, so I decided to convert it to JSON: getData(dataPlan: Data): Observable<Response<InfoType[]>> { return this.client.get<Response< ...

How can we eliminate the modal-open class in Angular when transitioning to a different URL?

Currently, I am facing an issue with a bootstrap modal. There is a button inside the modal which upon clicking should navigate the current component to another component named 'questions'. The problem arises when the new component is loaded, as t ...

Guide to creating varying component sizes using ReactJS and Styled Components

Is it possible to add variation to my button based on the prop 'size' being set to either 'small' or 'medium'? interface Props { size?: 'medium' | 'small'; } How can I adjust the size of the component us ...

Is the div's border linked to the routerlink directive?

Recently, I've been facing an issue with div elements using routerLink that are getting a blue border when clicked. It seems like there might be something obvious that I'm missing, whether it's a configuration in my browser or a CSS styling ...

Having trouble getting url-loader to function properly with a customized webpack configuration in an Angular 8

I am currently implementing custom webpack to integrate webpack with Angular 8. My goal is to use url-loader to inline SVGs, as the server where the app will be deployed does not support the SVG image/svg+xml mimetype (and unfortunately, I cannot change th ...

Switch on a single component of map array utilizing react and typescript

I am currently working on mapping a reviews API's array and I encountered an issue where all the reviews expand when I click on "read more" instead of just showing the clicked review. Since I am new to TypeScript, I'm not sure how to pass the ind ...

What is the best way for me to access the values of additional columns in the same row after triggering an event from a mat-select dropdown menu?

I am currently working with Angular 7 material and I have a situation where I need to retrieve data from all elements in the same row of a mat-table during the selectionChanged event of a mat-select dropdown. While I can successfully get the selection that ...

Angular 2 Custom Pipe Magic

I'm brand new to using the Angular 2 framework and I'm attempting to create a custom filter. app.component.ts import {Component} from 'angular2/core'; import {HTTP_PROVIDERS} from 'angular2/http'; @Component({ selector: ...

Retrieve the product IDs by selecting the checkboxes, then compile a fresh array consisting of the identified IDs

I am currently delving into the realm of typescript/angular2+ as a fledgling student, and I have taken on the task of creating a website to put my newfound knowledge to the test. The view is up and running, but I'm facing some roadblocks as I work on ...

What are some effective methods for resetting a state in @ngrx/store?

Lately, I've been grappling with a problem that's been on my mind for the past few days. Our team is developing an Angular 2 application, and my task involves creating a wizard for users to complete a form. I've successfully set up the dat ...

Mastering the art of understanding Data Binding

Embarking on a journey to learn about Angular and diving deep into the realm of data binding. On https://angular.io/guide/architecture-components, an illuminating visual halfway down the page visualizes the directional flow of data between the DOM and a C ...

Issues encountered when trying to implement a Navbar drop-down menu using Angular in conjunction with Bootstrap 4

I'm currently working on a web application using Angular 5 and Bootstrap 4, and I've encountered issues with the navigation menu bar dropdowns. Despite following the guidelines provided in the official documentation here, I can't seem to get ...

Developing UIs in React that change dynamically according to the radio button chosen

Problem Statement I am currently developing a web application feature that computes the heat insulation factor for a specific area. You can view the live demonstration on Codesandbox <a href="https://codesandbox.io/p/github/cloudmako09/btu-calc/main?im ...

Angular 2.0.0 - Simulated File Loader

For my unit testing, I am facing the challenge of mocking the FileUploader class from ng2-file-upload. Can anyone guide me on how to accomplish this? import { FileUploader } from 'ng2-file-upload/ng2-file-upload'; @Component({ selector: &apos ...

"Silently update the value of an Rxjs Observable without triggering notifications to subscribers

I'm currently working on updating an observable without alerting the subscribers to the next value change. In my project, I am utilizing Angular Reactive Forms and subscribing to the form control's value changes Observable in the following manner ...

Storing references to the DOM elements external to the rendering component

Just diving into the world of Electron + Typescript, so please bear with me. Currently, I'm experimenting with what can be achieved within Electron. Issue: My goal is to manipulate DOM elements outside of the renderer. I pass a button as a parameter ...

What is the best way to establish a restriction on the number of items obtained from an RSS

I am receiving a feed from this specific link. My goal is to only retrieve the initial five items from the feed, but currently I am getting all of the items. Is there a way for me to specifically request only the first five items? Do I need to include an ...

Specialized Character Formats in TypeScript

In my quest to enhance the clarity in distinguishing different types of strings within my program - such as absolute paths and relative paths, I am seeking a solution that ensures functions can only take or return specific types without errors. Consider t ...

Issues encountered with rest arguments while setting up gtag

I am currently working on implementing a Google Tag loading script using TypeScript. const GTAG_ID = 'ID'; const script = document.createElement('script'); script.src = `https://www.googletagmanager.com/gtag/js?id=${GTAG_ID}`; ...

Exploring the implementation of a custom validator within an Angular service

I have been attempting to implement a custom validator to validate if an email is already in use. After consulting the documentation and reading various articles, I have come up with the following code: In my auth.service.ts file checkEmail(email) { ...