在Angular 7中,属性被默认设置为私有。如果你想在类外部访问该属性,你需要在属性前面加上public
关键字。
以下是一个示例代码,展示了如何在类外部访问一个在Component
类中的service
属性:
import { Component } from '@angular/core';
@Component({
selector: 'app-example',
template: '{{ service }}
',
})
export class ExampleComponent {
public service: string = 'Some service';
constructor() { }
}
// 在类外部访问service属性
const example = new ExampleComponent();
console.log(example.service); // 输出 'Some service'
请注意,这种方法只能在构建时使用,而在运行时无法使用。在运行时,你需要使用依赖注入的方式来获取service
属性的值。