Incorporate service providers into models with Ionic3/Angular4

I am seeking feedback from individuals with more experience than me to determine if my approach is correct. I am currently working on an Ionic3-Angular app that involves a CRUD functionality for "Clientes". From what I have researched, the recommended structure is as follows:

  • Cliente Model: A class where attributes are defined.
  • Cliente Service / Provider: Responsible for database communication, including retrieving, modifying, and saving data.
  • Page: Where data is loaded and displayed.

The examples I have come across typically involve:

  • Instantiating the Cliente model in the Page.
  • Injecting the Cliente Service / Provider into the Page.

When loading data:

  • Data is loaded from the Page using the Provider, then assigned to an object (of type Cliente).

Now, here's where my uncertainty lies - would it be more effective to implement data access and management directly within the Model? I have successfully completed small projects using this approach, but I haven't been able to find any existing examples of others doing the same. This leads me to question whether or not I might be mistaken. Essentially, my idea is to have a Client Class with these methods:

static load(cs:ClienteService,id):Cliente{
//Function that receives the provider and uses it to access data based on the provided Cliente ID.
}

guardar(cs:ClienteService):boolean{
// Function to save the object using the provided ClienteService parameter
}

The ClienteServicio will be injected into the Page and passed to the Model as a parameter when necessary. This way, logic checks data, etc., can all be managed within the Model itself.

I hope this explanation makes sense, and I welcome any advice from the community. Thank you very much!

Answer №1

It is recommended to utilize interface classes instead of model classes for better flexibility and maintainability. For a more in-depth explanation, you can refer to this article here

When creating Injectable services, ensure that you define the business logic for saving, fetching, and updating data. It is important that these data are returned as Observables.

In your component, you should subscribe to these services in order to receive the necessary data.

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

Simultaneously iterate through two recursive arrays (each containing another array) using JavaScript

I have two sets of arrays composed of objects, each of which may contain another set of arrays. How can I efficiently iterate through both arrays and compare them? interface items { name:string; subItems:items[]; value:string; } Array A=['parent1&ap ...

The error message "Unable to access property 'open' of an undefined menu" is being displayed in a TypeScript code

I am facing an issue with the action in my menu. For this project, I am using a material menu and icons. The main menu code appears as follows: <mat-menu #rootMenu="matMenu" [overlapTrigger]="false"> <ng-template matMenuContent let-element="ele ...

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 ...

Identifying the Click Event Within an ngx Bootstrap Modal

I recently set up an ngx bootstrap modal using the instructions provided in this helpful guide - . However, I'm facing a challenge in detecting click events within the modal body once it's open. Below is the code snippet from my app component. D ...

What is the best way to ensure the footer remains in an automatic position relative to the component's height?

I am struggling to position the footer component correctly at the end of my router-outlet. After trying various CSS properties, I managed to make the footer stay at the bottom but it acts like a fixed footer. However, I want the footer to adjust its positi ...

Tips for updating the date separator in Angular 2

When using the date pipe to format a date, I am struggling to change the date separator. My goal is to format the date as "27.07.2016". Despite trying the code below: {{dateValue | date:'dd.MM.yyyy'}} The output still displays the date as "27/0 ...

Exploring the integration of namespace with enums in TypeScript

In the angular project I am currently working on, we are utilizing typescript for development. One key aspect of our project is an enum that defines various statuses: export enum Status { ACTIVE = 'ACTIVE', DEACTIVE = 'DEACTIVE' } ...

What is a way to merge all the letters from every console.log result together?

I'm encountering an issue - I've been attempting to retrieve a string that provides a link to the current user's profile picture. However, when I use console.log(), the output appears as follows: Console Output: Below is my TypeScript code ...

How to vertically align Material UI ListItemSecondaryAction in a ListItem

I encountered an issue with @material-ui/core while trying to create a ListItem with Action. I am looking for a way to ensure that the ListItemSecondaryAction stays on top like ListItemAvatar when the secondary text becomes longer. Is there any solution to ...

Exploring JSON data in Angular

I am currently working with a Json file that contains two different objects: readers and books. Here is an example of the structure: { "users": [{ "id": 1, "username": "peterB", }, { "id": 2, "username": "MaryC" ...

What is a way to execute a series of requests using rxjs similar to forkJoin and combineLatest, without needing to wait for all requests to finish before viewing the results?

Consider you have a list of web addresses: urls: string[] You create a set of requests (in this instance, utilizing Angular's HTTPClient.get which gives back an Observable) const requests = urls.map((url, index) => this.http.get<Film>(url) ...

Exploring async componentDidMount testing using Jest and Enzyme with React

angular:12.4.0 mocha: "8.1.2" puppeteer: 6.6.0 babel: 7.3.1 sample code: class Example extends Angular.Component<undefined,undefined>{ test:number; async componentWillMount() { this.test = 50; let jest = await import('jest&apos ...

Guide for setting up various validations for formGroup in an Angular 5 project

I am currently working on implementing Angular reactive form validation. My existing structure only includes validation for required fields, but I am looking to add additional validations such as minLength, email, and postcode. One challenge I face is cre ...

Exploring resources within a library in Angular

I need help accessing assets from a shared library within my nx workspace. Here is the structure: /apps -- my-app // ... /libs -- shared -- assets -- resources -- translation.json The shared lib has an alias defined as @my-company/s ...

What are some ways to customize the functionality of the data table filter in Angular Material?

Attempting to use the filter feature in Angular Material Data Table: When searching for "MATCHED", both "MATCHED" and "UNMATCHED" are displayed in the status column of the table. It seems this is due to the data object being reduced and concatenated befo ...

What could be the reason for the absence of a TypeScript error in this situation?

Why is it that the code below (inside an arbitrary Class) does not show a TypeScript error in VSCode as expected? protected someMethod (someArg?: boolean) { this.doSomething(someArg) } protected doSomething (mustBePassedBoolean: boolean) { /* ... * ...

What is the result of using `X ? A : B` in typescript?

type TestAny = any extends 'a' ? 1 : 2 // => 1 | 2 why??? how to interpret? type TestUnknown = unknown extends 'a' ? 1 : 2 // => 2 type TestStringA = 'a' extends 'a' ? 1 : 2 // => 1 type SomeUnion = ' ...

There seems to be an issue with Firebase authentication on firebase-admin in node.js. Your client is being denied permission to access the URL "system.gserviceaccount.com" from the server

Issue I've been utilizing Firebase auth on my client and using firebase-admin to verify on the server. It was functioning well until I decided to migrate to a different server, which caused it to stop working. The crucial part of the error message i ...

How can you retrieve the property value from an object stored in a Set?

Consider this scenario: SomeItem represents the model for an object (which could be modeled as an interface in Typescript or as an imaginary item with the form of SomeItem in untyped land). Let's say we have a Set: mySet = new Set([{item: SomeItem, s ...

The module named "jquery" has not been loaded in this context: _. Please use require() to load it

As I work on migrating my Javascript files to Typescript, I encountered an issue when trying to use the transpiled javascript file in an HTML page. The error message I received is as follows: https://requirejs.org/docs/errors.html#notloaded at makeError (r ...