简体   繁体   中英

Variable exported from a module not accesible inside function of class in angular

I have a file (service file) in angular.I am exporting a variable from it and using it in other file(component.ts).

When i am accessing its value outside the class ,it is working fine ,but when I am using it inside any function declare inside component class ,it is showing variable not defined.

In angular every module have its own scope ,and ts file converted into js and classes into function. So according to my understanding of javascript,variable outside of function should be available. But when i assign it to some declared variable outside the class it is working.

Where am i lacking to understand this behaviour?

    import {UserService ,b} from './services/user.service';
    console.log(b);// working
    //var t=b; working

    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css'],
      providers:[UserService]
    })
    export class AppComponent implements DoCheck , AfterContentInit,AfterContentChecked {
      title = 'project';
      a:any="joshi";
      constructor(private vc: ViewContainerRef ,private user:UserService){
        console.log("parent constr")

      }
      update(){
        //t="changed";  working
        b="changed"  //not working
      this.user.setObservable();

  }
}

That is not possible because outside a module,a variable is treated as const . If it was an object, something like

export let b = { name:  "shashank" };

you could have been able to change it.

A workaround could be to create a function which can allow you to change its value from the inside of the module itself, something like:

export let b = "shashank";

export let setB = (value) => {
  b = value;
}

and in component :

update(){
  setB("Hero");
  console.log(b)
  this.user.setObservable();
}

That being said, I think you are doing something wrong. The b is inside the UserService , so it can be used as this.user.b rather than importing it explicitly.

The approach you using doesn't seem right (unless you have something more going on and you havent mentioned in the question)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM