angular - Angular - 需要在导出类的内部/外部定义哪些变量?
问题描述
在此处的 Angular 教程中:https ://stackblitz.com/angular/qmgqmlrqmye?file=src%2Fapp%2Fhero.service.ts
我们必须在导出的 HeroService 类之外定义 httpOptions 并在类内定义 heroUrl。将一个移动到类内部或外部会破坏应用程序。这是什么原因?我如何知道必须在内部或外部定义哪些变量?
代码示例:
import { HttpClient, HttpHeaders } from '@angular/common/http';
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
@Injectable({ providedIn: 'root' })
export class HeroService {
private heroesUrl = 'api/heroes'; // URL to web api
constructor(
private http: HttpClient,
private messageService: MessageService) { }
/** GET heroes from the server */
getHeroes (): Observable<Hero[]> {
return this.http.get<Hero[]>(this.heroesUrl)
.pipe(
tap(heroes => this.log(`fetched heroes`)),
catchError(this.handleError('getHeroes', []))
);
}
...
解决方案
你可以把这些东西放在课堂内外。我个人会把所有这些东西都放在课堂上,因为它们显然是课堂的一部分。
private
在类内部定义的成员或者以它们只能从类内部引用的含义开头,这public
意味着您可以从类外部引用它们,或者没有任何一个,这意味着它是隐式公共的。
让我们看看我们将如何httpOptions
在课堂上移动。由于它是一个只有类需要知道的实现细节,所以将它定义为私有成员是有意义的:
private httpOptions = {
headers: new HttpHeaders({'Content-Type': 'application/json'})
}
现在,由于它是一个类成员,为了访问它,我们必须使用this
. this
只是对类上下文的引用,所以我们说给我this
类中的成员。
您看到httpOptions
被引用的任何地方都将其更改为this.httpOptions
希望您能看到如何以相反的方式进行操作,并将它们定义为类之外的 const。
推荐阅读
- python - 如何在 Windows 10 上使用 avro-python3 解析文件?
- database - 如何找到主备实例应用的日志序列的差距?
- php - 为什么我的本地主机无法识别其目录中的 htdocs?
- salesforce - 我们如何使用 API 获取电子邮件模板的名称?
- r - 如何为 highcharter columnrange 图使用日期范围?
- postgresql - 生产中的 Express session、passport 和 connect-pg-simple 问题
- corda - Corda - VaultQueryException:请注册实体
- amp-html - 需要 amp-ad-custom 用法说明和示例代码
- c# - 错误“NullReferenceException:对象引用未设置为对象的实例”,我该如何解决?
- amazon-web-services - AWS Lambda 删除超过 7 天的对象