简体   繁体   English

生产模式中的AoT错误

[英]AoT errors in production mode

So in my project I have components and services and I have included services where I need them. 所以在我的项目中我有组件和服务,并且我已经包含了我需要的服务。 To do so I declared all the services as private in the constructor. 为此,我在构造函数中将所有服务声明为私有。 For example: 例如:

constructor(private myService: MyService) {}

But in the html template I have used the service like ([ngModel])="myService.name" . 但是在html模板中我使用了像([ngModel])="myService.name" And here is the issue, when I tried to build in production mode I had a lot of AoT errors saying that I was using a private property which was only accessible within the class for each service I used in an html template. 这就是问题,当我尝试构建生产模式时,我有很多AoT错误,说我使用的私有属性只能在类中为html模板中使用的每个服务访问。 So I was wondering if it's a good practice to declare all the services as public to avoid the AoT errors. 所以我想知道将所有服务声明为公开以避免AoT错误是一种好习惯。

You can either 你也可以

  • Add a public accessor to the property on the component that calls through to the service. 在调用服务的组件上向属性添加公共访问器。

     get name():string {return this.myService.name;} 
  • Change private to public in the constructor 在构造函数中将private更改为public

     constructor(public myService: MyService) {} 

As far as which of these 2 is "correct" is a matter of opinion. 至于这两个中的哪一个是“正确的”是一个意见问题。

Yes, you need to declare instance variables (eg your service) as public if you want to use them in a template. 是的,如果要在模板中使用它们,则需要将实例变量(例如您的服务)声明为公共变量。 Alternatively, declare a public method in your class so you don't have to use your service directly: 或者,在您的班级中声明一个公共方法,这样您就不必直接使用您的服务:

constructor(private userService: UserService) {}

getUsers(): User[] {
  return this.userService.getUsers();
}

Also, I'd recommend that you use AOT during development so that you get notified about those errors immediately. 此外,我建议您在开发期间使用AOT,以便立即收到有关这些错误的通知。 It should not take much longer anymore. 它不应该再花费更长的时间了。 ng serve --aot

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

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