简体   繁体   English

从模块导出的变量在 angular 类的函数内不可访问

[英]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).我在 angular 中有一个文件(服务文件)。我正在从中导出一个变量并在其他文件(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.在 angular 中,每个模块都有自己的作用域,ts 文件转换为 js,类转换为函数。 So according to my understanding of javascript,variable outside of function should be available.所以根据我对javascript的理解,函数之外的变量应该是可用的。 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 .这是不可能的,因为在模块外部,变量被视为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 :并在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. b位于UserService内部,因此它可以用作this.user.b而不是显式导入它。

The approach you using doesn't seem right (unless you have something more going on and you havent mentioned in the question)您使用的方法似乎不对(除非您有更多事情要做并且您没有在问题中提到)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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