In TypeScript/Angular, what is the best way to share model variables between a Service class and a controller class?

Is there a way for the Controller and Service classes to access the same model without explicitly passing it?

For example:

Controller Class :

import { SearchModel } from "../../models/SearchModel";
import { SearchService } from "../../components/SearchService";

export class SearchController {
    public searchModel: SearchModel;
    static $inject = ['searchService'];

    constructor(private searchService:SearchService) {
        this.searchService = searchService;
    }

    public controllerMethod() {
        console.log(this.searchModel.searchKeyword); //This works. 
        this.searchModel.searchKeyword = "CheckIfSharedObject";
        this.searchService.serviceMethod();
    }
}

Service Class :

import { SearchModel } from "../../models/SearchModel";

export class SearchService {
    public searchModel: SearchModel;

    constructor() { }

    public serviceMethod() {
        // This will not work. i.e this wont print 'CheckIfSharedObject'
        console.log(this.searchModel.searchKeyword);
    }
}

Model Class :

export class SearchModel {
    constructor (
        public searchKeyword: string
    )
}

In the given example, we want both the controller and service classes to share the model variable searchKeyword. It currently requires passing the model class object to the service method, but we are looking for a way to achieve this without explicit passing.

Answer №1

In order for both the controller and service to have access to the shared variable searchKeyword, they should utilize an angularjs service to handle the model.

By modeling the model with an angularjs service, you can create a singleton that is accessible to both the controller and the service. This ensures consistency in the data being used across both classes.

Consider making the service the main representation of the model to simplify the architecture to just "controller" + "service", although having three separate entities is also an option if needed.

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

The AngularJS uib-typeahead feature seems to be disrupting the interpolation process for the entire page

Encountering an issue with AngularJS 1.50 where interpolation stops working after a specific line of code. <input type="text" class="form-control" id="search" name="search" placeholder="{{ shouldInterpolateButDoesnt }}" typeahead-on-sel ...

Displaying tab content in AngularJS from a dynamic array

I am currently working on my very first Angular SPA project. Within a form, I have implemented three tabs and would like each tab to display its content only when selected. The contents of the tabs are stored in an array within the controller. I have spent ...

When determining the extent to which client-side code should be utilized

As I work on developing a website with an extensive admin section, I am contemplating the amount of logic to incorporate on the client side. Using Ruby on Rails, I have the option of generating admin pages solely server-side with light client-side code for ...

Organize information in a React table following a predetermined sequence, not based on alphabetical order

As a beginner with React, I'm looking to sort my data by the column "Status" in a specific order (B, A, C) and vice versa, not alphabetically. The data structure looks like this: export interface Delivery { id: number; name: string; amount: num ...

Arranging elements in a list according to their position on the canvas using AngularJS

I am currently working on drawing rectangles on an html5 canvas using the JSON format provided below. My goal is to sort the array based on the x and y locations of each element. { "obj0": { "outerRects": [ { "outerRectRoi": { "x1": 0, " ...

The performance of the Ionic app is significantly hindered by lagging issues both on Google

After starting to work with the ionic framework, I noticed a significant change in performance when testing an android app on Chrome for the first time. It was fast and responsive until I added a button that led to a screen with navigation bars, side men ...

Steps to create a clickable row with color change in Angular 4

How do I make an entire row clickable and change the row color when a checkbox is clicked? This is my HTML file: <section class="others"> <div class="sub-header">Others</div> <p class="text-center" *ngIf="otherTests.length === 0"> ...

Create an AngularJS task manager that saves your to-do list even when the page is refreshed

Currently, I am developing a straightforward to-do list application using AngularJS within an ASP.NET MVC template. Surprisingly, I have successfully integrated Angular and Bootstrap to achieve the desired functionality. The app allows users to add and re ...

Ensuring that Vue3 Typescript app focuses on input element within Bootstrap modal upon opening

I am facing a challenge with setting the focus on a specific text input element within a modal dialog. I have tried various methods but none seem to achieve the desired outcome. Here is what I have attempted: Attempt 1: Using autofocus attribute. <inpu ...

Ways to update a component upon becoming visible in Angular

Within my Angular 4.3.0 project, the header, left panel, and right panels are initially hidden on the login page until a successful login occurs. However, once they become visible, the data is not pre-loaded properly causing errors due to the ngOnInit meth ...

The Next.js app's API router has the ability to parse the incoming request body for post requests, however, it does not have the

In the process of developing an API using the next.js app router, I encountered an issue. Specifically, I was successful in parsing the data with const res = await request.json() when the HTTP request type was set to post. However, I am facing difficulties ...

Is it possible to create perfectly aligned pie charts in nvd3? Check out this code snippet to see how it can be achieved: http://plnkr.co/edit/w0LewO7TmG6Lx

Having just started with AngularJS, I am facing a challenge in creating two equal-size pie charts and aligning them horizontally. Currently, they are aligning vertically - the first chart on one row and the second on the next. Does anyone know how to alig ...

Tips for updating the value within a textfield in HTML

I am looking to dynamically update the value displayed in my Revenue textfield by subtracting the Cost of Goods from the Sales Price. I have included an image of the current layout for reference, but I want the Revenue field to reflect the updated value af ...

Angular: Navigating to another URL causes the page to revert back to the default route

Currently, I am working with Angular 1.3.10, ui-router 0.2.10, and Express 4.14.0 to develop a Reddit-style application, and I'm facing some issues with routing. The simplified version of my Express routes: router.get('/api/home', function ...

Ways to input a return value that may be an array depending on the input

I'm struggling to properly type the return value in TypeScript to clear an error. function simplifiedFn( ids: string | string[], ): typeof ids extends string[] ? number[] : number { const idsIsArray = Array.isArray(ids); const idsProvided = idsI ...

Tips for choosing the following row in an Angular user interface grid

How can I deselect the currently selected row and select the one that follows it by clicking a button? I am using AngularHotkeys.js for this purpose. It gets even more complicated because I can sort the table with different columns. It would be helpful to ...

Setting up vibration for local notifications in Ionic and Cordova is a straightforward process

Is there a way to enable vibration in local notifications on my mobile device for every notification I receive? Example of Local Notification Code: $cordovaLocalNotification.schedule({ id : remId, title : name.innerHTML, text : note.value, ...

I am having trouble getting Angular 6 to work with lowdb

I am currently in the process of developing an Electron app with Angular 6, utilizing lowdb as a local database. This is all very new to me and I am learning through trial and error. However, I seem to be encountering difficulty resolving the following er ...

Angular crashes and burns after attempting to clone from GitHub

Upon completing the cloning of an Angular Project from GitHub using git clone ---link, I encountered some errors when I ran "npm install". https://i.sstatic.net/cCGmY.png ...

Issue with ngShow not functioning when used within an HTML template

I'm struggling with displaying and hiding a div from a template on an HTML page. You can see a simple JSFiddle example here. app.directive('example', function () { return { restrict: 'E', template: '< ...