2

I am using Angular 2. For the global variable access, I created a service and injected it into my component pages.

I can access it in any page, but when I update that variable, the changes will not affect while accessing it in another page.

This is the code in the GlobaldataService:

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

@Injectable()
export class GlobaldataService {
    public var1="haii";
}

This is the service that I used:

constructor(public obj: GlobaldataService){}

In one of my component pages, I updated the variable by this.obj.var1 =" hello";

In another page component alert(this.obj.var1); But it displays the older value which is "haii" how can I update the global variable .

Thanks in advance.

2 Answers 2

6

What you want is a messenger service. It's keeping a global variable and offers your components an Observable to subscribe to as well as a method to update and broadcast a new value:

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject ';
import { Observable } from 'rxjs/Observable ';

@Injectable()
export class MessengerService {

    private messageSource: BehaviorSubject<string> = new BehaviorSubject('initialValue'); 
    public message = this.messageSource.asObservable();

    public setMessage(value: string) {
        this.messageSource.next(value);
    }
}

In your component, you're simply subscribing to the value and can update it:

import { Subscription } from 'rxjs/BehaviorSubject ';

export class ViewComponent implements OnInit, OnDestroy {

    private messageSubscription: Subscription;

    constructor(private messengerService: MessengerService) { }

    ngOnInit() {
        this.messageSubscription = this.messengerService.message.subscribe(m => {
            // Do something with your value
        });
    }

    ngOnDestroy() {
        this.messageSubscription.unsubscribe();
    }

    setGlobalValue(value: string) {
        // All components that are subscribed to the
        // messenger service receive the update
        this.messengerService.setMessage(value);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

If other components and services read var1 from your service, they creating a copy of the value. If you then later update the source, the others don't get notified about the changed source. They all would need to re-read the value from the global service.

If the value of var1 would be an object instead of a string and you don't replace the object but only modify a property of the object, the components and and services might get the updated value.

Primitive values like string, number, and boolean are copied by value, while objects are copied by reference.

The better option would be to use an Observable that allows interested components and services to subscribe to changes (actively get notified about updates).

The tutorials in http://angular.io and a lot of online tutorials show how to use observables.

2 Comments

thanks@ Gunter for the fast response and the valuable info. How can I create an object globally. I there any simple possible solution..?
"How can I create an object globally". Sorry, I don't understand what that means. If you provide a service in AppModule, it will be a global singleton.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.