Bidirectional Data Binding with Angular 2 Services

Wondering about the connection between salary.service and player.component in Angular 2. If the salary variable is updated in the service, will it automatically reflect in the view of the player component?

Initially, the player.component view displays a salary of 50000, showing that they are linked. However, I'm struggling to figure out how to update the value.

salary.service

export class SalaryService {

    public salary = 50000; // starting value to be subtracted from

    constructor() { }

    public setSalary = (value) => { this.salary = this.salary - value };

}

player.component

export class PlayerComponent {

    constructor(private salaryService:SalaryService) {}

    public salary = this.salaryService.salary;

    public updateSalary = (value) => { this.salaryService.setSalary(value) };

}

UPDATE

Resolved the issue by checking out the Plunker:

http://plnkr.co/edit/aFRXHD3IAy0iFqHe5ard?p=preview

Answer №1

It is important to note that the way you have defined

public salary = this.salaryService.salary
is simply copying the value and not creating a reference to it. This means that the salary in the player component and the one in the service are stored in different memory locations, hence they are not the same.

If you were to pass a player with a salary to the service for manipulation, then the view would reflect the changes accurately as it would be working on the correct object.

Here is an example:

import {Injectable} from "@angular/core";

@Injectable()
export class SalaryService {
    constructor() { }

    public setSalary = (player, value) => {
      player.salary -= value;
    };

}

player.component.ts

import { Component } from "@angular/core";
import { SalaryService } from "./salary.service";

@Component({
  selector: 'player',
  template: `
  <div>{{player.salary}}</div>
  <button (click)="updateSalary(player, 50)" type="button">Update Salary</button>
  `,
  providers: [SalaryService]
})
export class PlayerComponent {
    player = { id: 0, name: "Bob", salary: 50000};
    constructor(private salaryService:SalaryService) {

    }

    public updateSalary = (player, value) => {
      this.salaryService.setSalary(player, value);
    };
}

Feel free to experiment with this plunker link: http://plnkr.co/edit/oChP0joWuRXTAYFCsPbr?p=preview

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

Having trouble getting POST requests to work in Angular 8 for unknown reasons

Hey there! I'm currently experimenting with using POST requests to an API in Angular for the first time, but unfortunately it's not working as expected. I've checked out some other examples of code and everything seems fine. Here is a snipp ...

Encountering the error message "Receiving 'Multiple CORS header 'Access-Control-Allow-Origin' not allowed' while accessing my Laravel API from Angular"

After successfully developing an API with Laravel that functioned perfectly with Postman, I am now working on its front-end using Angular. However, I keep encountering this error every time I send a request to the API: Cross-Origin Request Blocked: The Sa ...

Access the system by authenticating with the Firestore database collection

My goal is to develop a function that retrieves information from my collection in order to log into my application. With the help of this service, I am able to fetch all the necessary data: getUsersLocal(): Observable<AdminUser[]> { const bo ...

What is the reason for my Angular2 application not being able to locate my model?

An error occurred: XHR error (404) loading Access the Plnkr link here: https://plnkr.co/edit/gwa3NWArtWK0wjf2jr2h?p=preview I have created a file named models/home.ts https://i.sstatic.net/FQlgi.png The file includes: export function homeData() { re ...

Diving into Angular Typescript: Understanding the [object Object] in HTML

One of my todos requires the following input: todo.ts: import { TodoTag } from "./todo-tag-custom"; export class Todo { ... tags: TodoTag[]; } todo.html <tr *ngFor="let todo of todosFiltered()"> <td>{{todo.tags | json ...

What is the proper way to implement an if-else statement within objects?

Is there a way to convert the code below into an object structure so I can access nodID and xID keys from different files? The issue lies in the if statement within the code. My idea is to use export const testConfig = {} and import testConfig into any fil ...

MatIconRegistry import error in Angular Material

Currently, I am using 'Angular: 10.0.14' along with '@angular/material 10.2.7'. However, when attempting to import MatIconRegistry, I encountered the following error message: ERROR in node_modules/@angular/material/icon/icon-registry.d ...

How should one properly deal with this situation when it comes to the 'ngChanges' function?

Providing a downloadable data to a child component using the @input value has been working smoothly. Users can click on the download link and the file is downloaded without any issues. However, when changes are detected and the ngOnChanges function is tri ...

Struggling to populate a table with data

I've previously sought help on this project and I'm still facing challenges. The code is messy with duplicate functions, making it hard to manage. Currently, my main issue is fetching data from Firebase and updating a table with it. <div cla ...

The table component in Primeng is encountering issues when being used with ngFor

I'm attempting to iterate through an array where each object represents a table in HTML, and it should be displayed like this: <p-table [value]="section" *ngFor="let section of sections"> <ng-template pTemplate="header"> <t ...

Link the chosen selection from a dropdown menu to a TypeScript object in Angular 2

I have a form that allows users to create Todo's. An ITodo object includes the following properties: export interface ITodo { id: number; title: string; priority: ITodoPriority; } export interface ITodoPriority { id: number; name ...

After a successful login API request, Angular is triggering an additional OPTIONS request for each subsequent API call

I've encountered a problem while using CodeIgniter as the backend and Angular 4 as a REST-based frontend client. It seems that every request is being sent twice - once using OPTION and then again using GET or POST. Here is a screenshot from the Conso ...

Maximizing the Capabilities of the IIS URL Rewrite Module

Is the IIS URL rewrite module suitable for commercial use? I am looking to deploy my angular app on IIS, but my company has suggested exploring alternative options. Can the IIS URL Rewrite module not be used for commercial purposes? Are there any other a ...

Creating a local HTML file using node.js: A step-by-step guide

Recently, I've delved into developing games using Typescript. However, I've encountered a bit of an issue when attempting to build my game - it requires running on a server. This limitation prevents me from creating an offline game with Node.js a ...

How come my button is initiating automatically instead of manually?

Working on developing an API using Angular 2 with the Janus media server has brought up an issue regarding the start button. When running Janus, the button initiates automatically instead of manually. The following function was implemented for this purpos ...

The process of hosting an Angular 2 project on Azure begins by navigating to the

Embarking on a new journey in angular2 project development. Seeking guidance on deploying an angular2 project on the Azure portal. I have successfully deployed my project on Azure using a Bitbucket repository. However, upon accessing , I encountered the ...

Obtaining additional information for Observable<Object[]>

I have a scenario where I am working with a service that returns Observable<Object[]>. Each Object in the array has a subObjectId property. My goal is to populate the object's subObject property with data retrieved from another service. How can ...

Determine whether or not there are any duplicate elements within an array object

Is there a way to determine true or false if there are any duplicates within an object array? arr = [ { nr:10, name: 'aba' }, { nr:11, name: 'cba' }, { nr:10, name: 'aba' } ] arr2 = [ { year:2020, cit ...

Dealing with API Errors in Ngrx

I came across an interesting scenario in the ngrx example-app provided on Github. When starting a new project, I always strive to follow the best practices, so I referred to the example app for guidance. In one particular instance within the application, t ...

Attempting to utilize a namespace-style import for calling or constructing purposes will result in a runtime failure

Using TypeScript 2.7.2 and VSCode version 1.21 with @types/express, I encountered an issue where in certain cases VSCode would report errors like: A namespace-style import cannot be called or constructed, and will cause a failure at runtime. Interestingly ...