Angular: accessing public properties

I have a component called "user.service.ts" that I want to share.

import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions, Response } from '@angular/http';
import { AppConfig } from '../app.config';
import { User } from '../_models/index';

@Injectable()
export class UserService {
    constructor(private http: Http, private config: AppConfig) { }

    id: number = 0;
    Apt: number = 0;
 }

Now, I have two components:

Component 1:

import { UserService } from '../_services/user.service'

@Component({
    moduleId: module.id,
    templateUrl: 'index.html',
    styleUrls: ['userrentsettings.component.css'],
})

export class UserRentSettingsComponent implements OnInit {

    constructor(
        public userService: UserService);
         }


   ReadData(){
             this.userService.id = 10;
             this.userService.Apt = 10;
             }

Next, on the second component, I am trying to read the data:

import { UserService } from '../_services/user.service'

@Component({
    moduleId: module.id,
    templateUrl: 'index.html'
})

export class User2 implements OnInit {


    constructor(
        public userService: UserService);
         }
             
   ReadData(){
      console.log(this.userService.id);
      console.log(this.userService.Apt);
 }

The UserService is also configured as a provider in the app.module.

However, the result on the console shows "0" - but why?

Answer №1

Make sure to invoke the ReadData function.

import { UserService } from '../_services/user.service'

@Component({
    moduleId: module.id,
    templateUrl: 'index.html',
    styleUrls: ['userrentsettings.component.css'],
})

export class UserRentSettingsComponent implements OnInit {

    constructor(public userService: UserService) {
         this.ReadData();
    }

             
   ReadData(){
             this.userService.id = 10;
             this.userService.Apt = 10;
             }

Answer №2

We have identified the problem: The issue was caused by utilizing a bootstrap template that had: a href="/comp2" instead of using: [routerLink]="['/comp2']"

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 is the best way to receive a notification once the final observable has completed emitting its values?

In the past, we only made one call to the API reqFinanceDataWithFilters(req): Observable<any> { return this.http.post(env.baseUrl + req.url, req.filters) .pipe(map(this.extractResults)); } However, the response from this single request was a ...

Troubleshooting problems with Angular 6 update through the command "ng update"

https://i.stack.imgur.com/LuPSs.png I am currently in the process of upgrading from Angular version 5 to 6. When using the "ng update" command, I encountered a problem that is shown in the attached screenshot. Can someone guide me on how to resolve this ...

The recent transition to Angular 9 Subject has led to the emergence of the ExpressionChangedAfterItHasBeenCheckedError

Upon updating to Angular version 9, I encountered a series of errors stating: "Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value for 'hidden': 'true'. Current value: 'fa ...

Mono repo project utilizing Angular 4+ and Typescript, enhanced with Bootstrap styling

Looking for a project to practice with Angular 4+ using Typescript and a Bootstrap template. Hoping for a setup where I can just run npm install and ng serve to start. Any recommendations for mono repos would be highly valued! ...

Refreshing Angular 4 route upon modification of path parameter

I have been struggling to make the subscribe function for the params observable work in my Angular project. While I have successfully implemented router.events, I can't seem to get the subscription for params observable working. Can anyone point out w ...

Issue with Angular 2 HTTP provider: Observable subscription not triggering

I'm struggling to trigger the .subscribe() method on an observable in Angular 2. I have a provider that uses the Http Service to fetch data and return an observable for the controller to subscribe to. I can't figure out why the subscribe functio ...

Dynamically Disabling Form Control in Angular 2

There is a basic form with two form controls that initially have required validation. In addition to the form controls, there is a button in the template. When this button is clicked, it triggers a change in the behavior of the form group. Both form contr ...

Double firing issue with ngModelChange when paired with ng DateTimePicker in Angular 7

When utilizing the ng datetimepicker library in Angular to display a date time picker, I'm experiencing an issue where the method triggered by (ngModelChange) fires twice simultaneously, causing the changed date to be logged twice in the console. Can ...

Encapsulate the HTTP request within a common function for reus

My rest-provider service handles all of my http calls, but I've noticed that each function is repeating a lot of the same http code. It seems like I should create a shared function to avoid this repetition and make it easier to update in the future. ...

What steps should we take to ensure that the container beside the fixed left navigation bar is responsive?

Currently, I am working on creating a user interface that features a fixed navigation bar on the left hand side and a responsive content window. Here is what I have implemented so far: <div style="width: 15%; float: left; display: inline;"> <na ...

What is the best way to pass data between sibling components in Angular?

Within my Angular application, I have three sibling components that share a variable called "data". This data contains sensitive information related to API endpoints for determining discounts. Due to security concerns, passing this data through the router ...

Retrieving data through an Angular Material Table by employing an HTTP GET request

I am working with an Angular Material table and need to retrieve data from a service. Below is the code for the service. import { Injectable } from "@angular/core"; import { HttpClient } from "@angular/common/http"; import { Message } from '../messag ...

Having difficulty resolving all parameters for the component: (?, [object Object]) in the Jasmine component Unit Test

While defining a UT for a component with an extended class using i8nService and ChangeDetectionRef, I encountered an error preventing me from instantiating it: Failed: Can't resolve all parameters for BrandingMultiselectComponent: (?, [object Object] ...

Angular 2: Simplifying the Process of Retrieving a Full Address Using Latitude and Longitude

Currently, I am utilizing the angular 2-google-maps plugin. Is there a way to retrieve the country and postal code based on latitude and longitude using Angular 2 Google Maps with Typescript? ...

Encountering issues when integrating an Angular library project into the main project

Currently, I am facing an issue with a library project (let's call it X) that contains 2 projects within it (X-core, X-core-members). My goal is to utilize this library in another angular project called ABC. I have made the necessary links in the tsco ...

Establish a connection between two ionic and angular applications using a node server

Currently, I am managing two Ionic applications that both interact with the same API hosted on a node server. My goal is to enable one app to send a post request and have the other app receive and utilize the information from that request. I was consider ...

Ways to align the navigation icon to the left side

I need help positioning my help icon at the bottom of the screen, regardless of the user's monitor size. I've tried using margin and margin-top, but it doesn't adjust properly when changing monitor sizes. Any suggestions or assistance would ...

Tips for avoiding Angular routing when clicking on a Bootstrap tab link

I'm working on creating a bootstrap tab, but I'm running into an issue. Every time I click on the tab links, angular seems to be handling its own routing and redirecting me to a different route. What I really want is for the tab content to open u ...

A pronounced distinction exists between ionInput and ionChange functionality

Q. Can you explain the difference between (ionInput) and (ionChange) events in Ionic framework? When would it be more appropriate to use one over the other? I have experimented with both event handlers below and found that they produce the same expected r ...

Sending information from the AppComponent to another component that is loaded at a separate time

Is there a way for me to maximize efficiency when fetching data from a service in the AppComponent and then passing it on to another component that's loaded later? I'd like to minimize API calls by reusing the same data in multiple places. How ca ...