Discover the process of accessing and setting values in Angular 8 to easily retrieve and manipulate data from any page!

Greetings! I am currently utilizing Angular 8 and I have a query regarding how to access the set value in any given page.

Here is a snippet of my code:

class.ts

export class testClass {

        get test():string{
            return this.sexe;
        }
        set test(val:string){
            this.sexe = val;
        }

    }

In child.ts:

import { testClass } from '../class';
export class Child {
constructor (private test:testClass){}

test() {
this.test.test = "hello";
}

In parent.js:

import { testClass } from '../class';
export class Parent {
    constructor (private test:testClass){}

    test() {
    console.log(test.test);
    }
}

Within app.module.ts:

import { testClass } from '../class';
 providers: [testClass],

I seem to be encountering an issue where "test undefined" is showing up in parent.js. What could I possibly be doing wrong?

Answer №1

Not entirely clear on what you mean by setting and retrieving the value on any page. Are you referring to a component perhaps?

If so, I would recommend using a service like this

@Injectable({
  providedIn: 'root'
})
export class ExampleService{

  private _value: any;
  private _valueObs$ = new BehaviorSubject(null);

  set setValue(newValue: any): void{
    this._value = newValue;
  }

  get getNewValue(): any{
    return this._value;
  }

  set setObservableValue(newValue: any): void{
    this._valueObs$.next(newValue)
  }

  get getNewObservableValue(): any{
    return this._valueObs$;
  }
}

The method above demonstrates two approaches; the first being a standard set and get, while the second utilizes a Subject. The difference between the two will be discussed in the following section.

To implement this service in any component:

@Component({
  selector: 'example',
})
export class ExampleComponent implements OnInit {

  newValue: any;

  constructor(private readonly exampleService: ExampleService
  ) { }

  ngOnInit(): void {
    this.getObservableExampleValue();
  }

  getExampleServiceValue(): any {
    this.exampleService.getNewValue;
  }

  setExampleServiceNewValue(value: any): void {
    this.exampleService.setNewValue = value;
  }

  getObservableExampleValue() {
    this.exampleService.getNewObservableValue.subscribe((newObsValue) => {
      this.newValue = newObsValue
    })
  }

  setObservableExampleValue(value: any): void{
    this.exampleService.setObservableValue(value);
  }

  ngOnDestroy(){
    this.exampleService.getNewObservableValue.unsubscribe();
  }

}

No need to delve into the details of setValue & getNewValue; feel free to use them as needed.

The second approach is particularly useful if you want multiple components to be aware of a specific value simultaneously. For instance, setting the _valueObs$ with the setObservableValue method will notify all 5 components using this service about that value – quite handy, isn't it?

Remember to invoke getNewObservableValue to open the stream and make the value accessible for your component's template/code, typically done during ngOnInit. Subscribing to observables works akin to turning on a tap.

Imagine turning on a tap – that's subscribing

this.exampleService.getNewObservableValue.subscribe((newObsValue) => {
          this.newValue = newObsValue
        })

The tap is now running, emitting a stream of water (or data here); thus, every time a new value is set, it flows through the stream updating this.newValue in your component automatically.

However, remember to turn off the tap when not needed to avoid wastage – unsubscribe when the component is no longer active

ngOnDestroy(){
    this.exampleService.getNewObservableValue.unsubscribe();
  }

This prevents memory leaks, which are beyond this scope of discussion. For more on Rxjs, consider reading documentation at https://www.learnrxjs.io/ or watch tutorials on YouTube. Feel free to comment if further clarification is needed.

Answer №2

Using a service is essential.

Services are initialized when the application launches and remain active until it shuts down. By passing a value through a service, you make it accessible from anywhere within the service's scope.

For example, consider the following:

@Injectable()
export class ExampleService {
    public varIWant: string = 'I want to use this anywhere.'
}

You can utilize this value in your components like so:

import { ExampleService } from '../my/path/to/service'
export class Parent {
    constructor(private exampleService: ExampleService) { }

    public setVarAsLocal: string = this.exampleService.varIWant;

    public changeServiceVariable() {
        this.setVarAsLocal = 'New Value For String';
        this.exampleService.varIWant = this.setVarAsLocal;
    }
}

That's all there is to it. As long as the service instance remains active, the value will persist;

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

Compilation in TypeScript taking longer than 12 seconds

Is anyone else experiencing slow TypeScript compilation times when building an Angular 2 app with webpack and TypeScript? My build process takes around 12 seconds, which seems excessively slow due to the TypeScript compilation. I've tried using both ...

Incorporate image into Vue.js form along with other information

I have been successfully sending the content of multiple fields in a form to the Database. Now I am looking to add an additional field for uploading images/files and including it with the other form fields, but I am unsure about how to accomplish this task ...

typescript - transforming text into numerical values

newbalance = (Number(this.balance)) + (Number(this.pastAmount)); The result for my newbalance calculation is coming back as undefined, even though this.balance is 34 and this.pastAmount is 23. I've set this up in the controller and I'm trying t ...

What is the best way to extract all of the JSON data from Firebase using a web platform?

As a newcomer to Firebase and noSQL databases, I'm encountering difficulties in extracting all the JSON data from the database. Although I've gone through the firecast tutorials and understand how to retrieve specific values by referencing the da ...

Creating a progressive prototype chain in TypeScript: A step-by-step guide

With JavaScript, it is possible to create a "derived class" whose "base class" is dynamic using code like the following: function NewBaseClass(sF) { function DynamicBaseClass(iF) { this.instanceField = iF; } // EDIT: oops, this is not really static i ...

How can Observables be designed to exhibit both synchronous and asynchronous behavior?

From: Understanding the Contrasts Between Promises and Observables In contrast, a Promise consistently operates asynchronously, while an Observable can function in synchronous or asynchronous manners. This presents the opportunity to manipulate code in ...

Exploring Angular5 Navigation through Routing

I have been working with Angular routing and I believe that I may not be using it correctly. While it is functional, it seems to be causing issues with the HTML navbars - specifically the Info and Skills tabs. When clicking on Skills, a component popup s ...

Getting JSON data from an Angular JS controller can be achieved by utilizing the built-in

My user login function includes a method called logincheck, which takes in parameters and sends a request to the server. Upon success, it redirects the user to the dashboard with the member ID. this.logincheck = function(log) { var pa ...

Tips for looping through a JSON object?

Similar Question: How to extract a specific value from a nested JSON data structure? I am looking to loop through a two-dimensional JSON object, whereas I already know how to do so for a one-dimensional JSON object. for (var key in data) { alert(data ...

Where do I find the resultant value following the completion of a video production through editly?

Hey there, I have a quick question... I was following the instructions in the README for editly, and I successfully created videos by calling editly like this: // creating video editly(editSpec) .catch(console.error); The only issue is that I am using Ex ...

When an input event is dispatched in a unit test, the value changes of a form are not activated

Currently, I am testing a scenario where I need to verify if a value changes on the form when input is typed in. This particular project utilizes Nrwl nx as well as jest for testing purposes. The component code snippet is as follows: export class InputNu ...

Issue with alignment in the multiselect filter of a React data grid

In React Data Grid, there is a issue where selecting multiple filter options messes up the column headers. Is there a solution to display selected filter options above a line in a dropdown rather than adding them to the column header? The column header siz ...

Step-by-step guide on executing a multi-location "delete" operation using AngularFire2 or Firebase in Angular2

My goal is to simultaneously remove 2 nodes on Firebase in a single operation. I am familiar with the remove() function for deleting a node when I have its location. However, I am unsure about what type of data the remove() operation returns - whether it i ...

The positioning of images on the fabricjs canvas seems to be unreliable and inconsistent

When trying to place a series of 4 images at specified coordinates in fabricjs, I am facing inconsistencies with their placement upon page load. Refreshing the page usually resolves the issue, but I want to prevent this from happening altogether. If anyon ...

Tips for pressing the enter key to submit when faced with two buttons

I am developing a form with two input fields and their respective submit buttons. I want users to be able to enter text into either field, hit the Enter key, and have it trigger the same action as clicking the submit button. Currently, pressing Enter after ...

Analyzing DynamoDB Query

I am on a mission to recursively analyze a DynamoDB request made using the dynamo.getItem method. However, it seems that I am unable to locate a similar method in the DynamoDB SDK for Node.js. You can find more information about DynamoDB SDK at http://do ...

Determine if the user has clicked on the Save or Cancel button within the print dialog box

Hello everyone, Can anyone help me figure out how to determine which button was selected by the user in a print dialog box? Thank you! ...

Vue instance with non-reactive data

I am looking to store an object in Vue that will be accessible throughout the entire instance but does not need to be reactive. Typically, if I wanted it to be reactive, I would use 'data' like this: new Vue({ data: myObject }) However, since ...

How can I assign a specific class to certain elements within an *ngFor loop in Angular?

I have a situation where I am utilizing the *ngFor directive to display table data with the help of *ngFor="let record of records". In this scenario, I am looking to assign a custom CSS class to the 'record' based on specific conditions; for exam ...

Destructuring part of an object within function parameters in JavaScript

Is it possible to selectively destructure specific object properties in function arguments, while keeping the rest accessible within the object? Let's explore this concept with a React example. (Although React is used here, the question pertains to J ...