How to Update Global variable in angular2

前端 未结 2 1957
遇见更好的自我
遇见更好的自我 2021-01-07 03:24

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

2条回答
  •  悲哀的现实
    2021-01-07 04:02

    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.

提交回复
热议问题