Sum*_*uri 65 typescript typescript-typings angular2-aot angular
我正在尝试构建用于生产的 angular2应用程序,因为我正在关注此博客.在我的ngc成功编译后,当tsc编译发生时,它会生成以下错误,如图所示:
在搜索了一段时间后,我发现这个博客解释了"上下文属性"部分中的问题,我无法正确理解它可能会给你一些好主意,发生了什么错误.基本上当我们将变量设为私有时,我们会得到"错误:属性是私有的,只能在类中访问".我不明白为什么会这样.
请帮助我们,因为我们在过去的几天里一直在讨论这个问题.
小智 95
对于给定组件,其模板访问的所有成员(方法,属性)必须在AOT编译方案中是公共的.这是因为模板被转换为TS类.生成的类和组件现在是2个单独的类,您不能访问跨类的私有成员.
简而言之:如果要使用提前编译,则无法访问模板中的私有成员.
为了更好的解释https://github.com/angular/angular/issues/11422
Sum*_*uri 13
所以我解决了这个问题,我会保持简短.为解决这个问题,我深入阅读了这篇博客 在" 上下文属性 " 部分中解决此问题的方法是,如果要在使用AOT(即,Ahead Of Time)创建构建时直接在视图中使用它,请不要使用或创建私有变量生产.
*例如*
// component.ts
@Component({
selector: 'third-party',
template: `
{{ _initials }}
`
})
class ThirdPartyComponent {
private _initials: string;
private _name: string;
@Input()
set name(name: string) {
if (name) {
this._initials = name.split(' ').map(n => n[0]).join('. ') + '.';
this._name = name;
}
}
}
Run Code Online (Sandbox Code Playgroud)
输出: 属性'_initials'是私有的,只能在类'ThirdPartyComponent'中访问.
解:
将此更新private _initials: string;为简单_initials: string;
对于这个答案,Harish Gadiya为我提供了一些帮助.
小智 6
这对我有用:只需将服务更改为公共服务。
constructor(public service: SpecificObjectService) { }
Run Code Online (Sandbox Code Playgroud)
应用程序在生产中工作!!
当我在构造函数中声明私有可注入对象时,我得到了这个:
constructor(private service: SpecificObjectService) { }
Run Code Online (Sandbox Code Playgroud)
并在模板中使用它们:
*ngFor="let pd of service.listSpecificObject "
Run Code Online (Sandbox Code Playgroud)
解决方案是:
constructor(public service: SpecificObjectService) { }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
41758 次 |
| 最近记录: |