Tips for updating a service variable value within a component

My goal is to pass user input to the deviceName string in my component, which should then be passed to the deviceIP string in my service. It seems like the order of using get/set methods might be incorrect. Can someone help me identify the mistake?

Below is the code for my component:

@Component({
selector: 'app-section-computer-management',
templateUrl: './section-computer-management.component.html',
styleUrls: ['./section-computer-management.component.css'],
})

export class SectionComputerManagementComponent implements OnInit {
ping: number = 0;
public deviceName = 'cstorch-3420';

constructor(private _pingService: PingService) {
this._pingService.pingStream.subscribe(ping => {
  this.ping = ping; });
}

changeDIP(val){
  this._pingService.setDIP(this.deviceName);
}

showDIV() {
  alert(`GV ${this._pingService.getDIP}`);
}



ngOnInit() {}
}

Here's the code for my service:

@Injectable()
export class PingService {
pingStream: Subject<number> = new Subject<number>();
ping: number = 0;


deviceIp = "";
url = `http://${this.deviceIp}`;

setDIP(val: string) {
this.deviceIp = val;
}
getDIP(val: string) {
return this.deviceIp;
}

constructor(private _http: Http) {
interval(1000)
  .subscribe((data) => {
    let timeStart: number = performance.now();

    this._http.get(this.url)
      .subscribe((data) => {
        let timeEnd: number = performance.now();

        let ping: number = timeEnd - timeStart;
        this.ping = ping;
        this.pingStream.next(ping);
      });
  });
}
}

Following is the template I'm using:

<div class="section-container">
    <div class="cards">
        <div class="card-deck">
            <div class="card text mb-3 shadow card-theme">
                <div class="card-header card-header-theme text-center">
                    <h5>Please Enter A Device Name or IP Address</h5>
                </div>
                <div class="card-body">
                    <div ng-app="">
                        <p align="center"><input class ='form-control input-lg' 
    style= "width:300px" [(ngModel)]="deviceName" type="text"> {{deviceName}} 
    </p> 

                    </div>
                </div>
            </div>
            <div class="card text-center mb-3 shadow card-theme">
                <div class="card-header card-header-theme">
                    <h5>Machine Ping</h5>
                </div>
                <div class="card-body">
                        {{ping | number:'1.0-0'}}ms
                </div>
            </div>
        </div>
            <div class="row-fluid cards">
                <div class="card shadow card-theme">
                    <div class="card-body">

                    </div>
                    <div class="col-sm-2">
                            <div class="card shadow card-theme">
                              <div class="card-body">
                                <h5 class="card-title">Special title treatment</h5>
                                <p class="card-text">With supporting text below as a natural lead-in to additional content.</p>
                                <a href="#" class="btn btn-primary">Go 
somewhere</a>
                              </div>
                </div>
            </div>
        </div>
    </div>

Lastly, here's the module.ts file contents:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { NavbarComponent } from './navbar/navbar.component';
import { SidebarComponent } from './sidebar/sidebar.component';
import { SectionDashboardComponent } from './Sections/section-dashboard/section-dashboard.component';
import { SectionComputerManagementComponent } from './Sections/section-computer-management/section-computer-management.component';
import { SectionHelpdeskLinksComponent } from './Sections/section-helpdesk-links/section-helpdesk-links.component';
import { BarChartComponent } from './charts/bar-chart/bar-chart.component';
import { LineChartComponent } from './charts/line-chart/line-chart.component';
import { PieChartComponent } from './charts/pie-chart/pie-chart.component';
import { ChartsModule } from 'ng2-charts';
import { HttpClientModule, HttpClient } from '@angular/common/http';
import { freshServiceService } from './Services/freshservice.service';
import { PingService } from './Services/pingservice.service';
import { HttpModule } from '@angular/http';
import {FormsModule} from '@angular/forms';

@NgModule({
  declarations: [
    AppComponent,
    NavbarComponent,
    SidebarComponent,
    SectionDashboardComponent,
    SectionComputerManagementComponent,
    SectionHelpdeskLinksComponent,
    BarChartComponent,
    LineChartComponent,
    PieChartComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    ChartsModule,
    HttpClientModule,
    HttpModule,
    FormsModule,
  ],
  providers: [freshServiceService, PingService, HttpClient],
  bootstrap: [AppComponent]
})
export class AppModule { }

Answer №1

The function named setDIP exists within your component, however it appears that this function is not being utilized. To remedy this, you must ensure that the setDIP function is called whenever something is entered into an input field. This can be achieved by capturing the change event on the input field and then executing the setDIP method.

To implement this change, adjust your code as follows:

<p align="center"><input class='form-control input-lg' style="width:300px" 
    [(ngModel)]="deviceName" (change)="setDIP($event.target.value)" type="text> {{deviceName}} 
</p> 

Answer №2

Exploring the utilization of getters and setters in TypeScript:

Within MyService.ts

_counter: number = 0;

public set counter(counter: number) {
  this._counter = counter;
}

public get counter() {
  return this._counter;
}

Inside component.ts

constructor(private service: MyService) {}

adjustCounter() {
  this.service.counter = 1;
  console.log(this.service.counter);
  // Output: 1
}

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 steps should I take to have a button initiate an AJAX request?

One of the tasks on my list involves a textbox and a button for interaction. Once text is entered into the textbox, I intend to trigger an AJAX request by clicking the button. The purpose of this AJAX call is to extract the text input and incorporate it i ...

Does using the useState() hook in React automatically empty out the input fields?

Every time I update a state in my React application, it mysteriously erases the content of my inputs like checkboxes and numbers. Let me share a simple example to demonstrate this issue. import React, { useState } from "react"; export default fun ...

Encountering TypeScript errors when trying to reference Angular2 within a Gulp setup

The issue at hand is: [11:16:06] TypeScript: 103 semantic errors [11:16:06] TypeScript: emit succeeded (with errors) I am currently using node v5.7.0 and npm 3.6.0 gulp -v: [11:26:58] Requiring external module babel-register [11:26:58] CLI version 3.9 ...

Refreshing data attribute following an ajax request

I have this page with a list of various job listings. Each job listing has a button labeled "Paid" that includes a data-paid attribute indicating whether the job is paid or not. Whenever the "Paid" button is clicked, it sends a request to my route which u ...

Troubleshooting Failures in RequireJs Optimization for Windows

Currently working on optimizing a requirejs-based project on a Windows system. I have placed the r.js.cmd in the Scripts folder, along with the nodeBuild.js file containing the configuration settings. ({ baseUrl: ".", paths: { jquery: "empty:" }, name ...

Place a DIV over targeted text using dynamic positioning

How can I dynamically position a DIV at specific characters within a long DNA sequence displayed as a single line on a webpage, using a mono-width font and JavaScript? I want the solution to be able to adjust to changes in font size made by the user. Here ...

How can I switch the values of two select components in React js when clicked?

I am working on a project where I have two select components positioned on the right and left side respectively, each with different values - A on the right side and B on the left side. Now, in response to a button click event, I need to swap component A t ...

Using Chart.js to display JSON data in a graphical format

I am facing an issue and need some help. I have gone through various tutorials and questions, but none of them seem to address my specific problem. When making an ajax request to my PHP file, I receive a JSON response like this (as seen in the console log) ...

Troubleshooting Typescript & Express Routing Issue

I am currently following a tutorial on how to set up a simple express-typescript application. However, I am encountering some difficulties with my routes not working as expected. Despite searching for similar problems and solutions, I haven't found an ...

Swapping out a Django template variable for a variable generated using JavaScript

I'm new to Django and Javascript (less than 3 weeks!) and I have a query that may seem naive, so any assistance would be appreciated. In my current code, I have an HTML table rendered with the following snippet: <table border="1" class="dataframe ...

Add an element to the parent body from an iframe with this easy tutorial!

Within the iframe, I have the following code snippet. <script type="text/javascript"> $(document).ready(function(){ $("body").append($("#ctap").html()); }); </script> I am looking to append the HTML content of #ctap to the par ...

The jQuery function triggers in the console upon first click but does not display in the browser. However, it shows up twice in the browser upon

I'm quite puzzled by this issue. In my javascript file, the jQuery functions (including the one located at the end of the page) seem to skip the first click event and respond twice on the second click. I am also utilizing Bootstrap in my project. App ...

When I attempt to conceal the filter within mat-table using *ngIf, I encounter an issue where I am unable to read the property 'value' due to it being

After creating a mat-table, I encountered an issue when trying to show and hide my input filter area using a button. If I use *ngIf="showInputFilter" to hide the filter area, I receive the error message Cannot read property 'value' of u ...

Create a unique HTML id dynamically using AngularJS

Hello, I am looking to create a unique identifier in html in the format 'a1', 'a2', etc. based on the values in the table. I am thinking of achieving this in the following way: <div ng-controller="ddController" > ...

Is it recommended to exclude the NGXS NgxsLoggerPluginModule for production deployments?

When developing, it's common to use the following imports: import { NgxsReduxDevtoolsPluginModule } from '@ngxs/devtools-plugin'; import { NgxsLoggerPluginModule } from '@ngxs/logger-plugin'; Is it recommended to remove these imp ...

How come my object is iterating from last to first in the for loop?

I need help understanding arrays. Here is my data: And here is my for loop: for (var data in statInfo["segment"][0]) { console.log(data) } After running the code, I got this result: The printed data is: segment5 segment4 segment3 segment2 se ...

What is the best method for displaying over 1000 2D text labels using three.js?

Currently, I am in the process of designing a floor plan that includes over 1000 2D meshes with shapeGeometry and basicMeshMaterial on the scene. I also need to incorporate 2D text within these meshes while ensuring that the text is hidden within the bound ...

Dispatching an asynchronous function error in React with TypeScript and Redux - the parameter type is not assignable to AnyAction

Currently, I am in the process of developing a web application that utilizes Firebase as its database, along with Redux and TypeScript for state management. Within my code, I have a dispatch function nested inside a callback function like so: export const ...

When is the right time to develop a new component?

Exploring the strategy behind determining when to create a new component in a web application using angularjs / angular has been on my mind lately. It seems like this concept could apply to all component-based front end frameworks as well. I understand th ...

What is the method to acquire the firestore reference type in TypeScript?

Here is the code I am working with: import { DocumentReference } from '@firebase/firestore-types' export type Recipe = { author: string title: string ingredients: { quantity: number ingredient: DocumentReference["path"] ...