global variable in angular2

501 views
Skip to first unread message

Vinu Prasad

unread,
Oct 30, 2017, 5:23:47 AM10/30/17
to Angular and AngularJS discussion
How can I globally declare a variable and can be accessed in each component page. How to make it possible ??

Sander Elias

unread,
Oct 30, 2017, 6:14:19 AM10/30/17
to Angular and AngularJS discussion
Hi Vinu,

The correct way to handle this is to create a service and inject that whenever you need it. But if you really want to have a global, just create one in the JS global scope, and use it where you need it. Typescript will complain, and you need to define it in each file you are going to use it, but it will work nevertheless. 

Regards
Sander

Vinu Prasad

unread,
Oct 30, 2017, 7:58:37 AM10/30/17
to ang...@googlegroups.com
tanks @ Sander . I  create a service and inject into my component pages as You said .

I can acces it any page , but when i update that variable the changes will not affect while accessing it in another page.
import { Injectable } from '@angular/core';

@Injectable()
export class GlobaldataService {

public var1="haii";
}


constructor(public obj: GlobaldataService){}

this is the service that i used . In one of my component page  , I update the variable by this.obj.var1 =" hello";

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

Thanks in advance



--
You received this message because you are subscribed to a topic in the Google Groups "Angular and AngularJS discussion" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/angular/1YPf1HEaQco/unsubscribe.
To unsubscribe from this group and all its topics, send an email to angular+unsubscribe@googlegroups.com.
To post to this group, send email to ang...@googlegroups.com.
Visit this group at https://groups.google.com/group/angular.
For more options, visit https://groups.google.com/d/optout.



--
Vinu Prasad
 

Sander Elias

unread,
Oct 30, 2017, 9:11:11 AM10/30/17
to Angular and AngularJS discussion
Hi Vinu,

Angulars CD will make sure it updates, as long as you don't assign primitives to other primitives. Primitives are copied by value and break the reference chain CD depends upon. Just assign, don't copy..

Regards
Sander
Reply all
Reply to author
Forward
0 new messages