Vim*_*edi 25 typescript angular
注入服务与public和private之间有什么区别.我看到大多数示例在angular组件中使用private关键字.使用公众会有什么影响吗?例如
constructor(public carService: CarService) { }
Run Code Online (Sandbox Code Playgroud)
与
constructor(private carService: CarService) { }
Run Code Online (Sandbox Code Playgroud)
Deb*_*ahK 33
除了先前的答案之外......组件的模板也无法访问标记为私有的任何内容.(私有成员可使用JIT时,例如在开发时使用AOT时,如用于生产被访问,但不是.)
因此,在您的模板中,您只能*ngIf='carService.isValid'
将注入的服务标记为public
.
但实际上,最佳实践是将任何服务属性/方法包装在组件属性/方法中,并让模板绑定到/调用组件的属性或方法.
像这样的东西:
get isValid(): boolean {
return this.carService.isValid;
}
Run Code Online (Sandbox Code Playgroud)
然后像这样访问它: *ngIf='isValid'
例如,对于您有服务的情况:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class CarService {
constructor() { }
public design = {
"color": "blue"
}
}
Run Code Online (Sandbox Code Playgroud)
在您将要实现服务的构造函数中
constructor(private carService: CarService) { }
Run Code Online (Sandbox Code Playgroud)
您可以使用正常方法返回服务
getCarService() {
return this.carService;
}
Run Code Online (Sandbox Code Playgroud)
在你的模板中你可以做
<div>{{getCarService().design.color}}</div>
Run Code Online (Sandbox Code Playgroud)
答案很简单:在不需要在当前类/组件之外使用私有变量时,必须创建私有变量,否则,应创建公共变量。还有一件事:您还可以使用私有变量,并通过称为getters和setters的特殊函数从外部访问它们。例如:
private _customValue: any;
set customValue(newValue: any): void {
this._customValue = newValue;
}
get customValue(): any {
return this._customValue;
}
Run Code Online (Sandbox Code Playgroud)
注意,这_customValue
是私有的,但是您可以通过使用以下操作从类外部设置/获取该值customValue
:
classInstance.customValue = 'newValue';
console.log(classInstance.customValue);
Run Code Online (Sandbox Code Playgroud)
需要说的是set
,get
在方法名称之前并不需要关键字,因此更需要澄清。
归档时间: |
|
查看次数: |
7545 次 |
最近记录: |