首页 > 解决方案 > 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', []))
    );
}
...

标签: angular

解决方案


你可以把这些东西放在课堂内外。我个人会把所有这些东西都放在课堂上,因为它们显然是课堂的一部分。

private在类内部定义的成员或者以它们只能从类内部引用的含义开头,这public意味着您可以从类外部引用它们,或者没有任何一个,这意味着它是隐式公共的。

让我们看看我们将如何httpOptions在课堂上移动。由于它是一个只有类需要知道的实现细节,所以将它定义为私有成员是有意义的: private httpOptions = { headers: new HttpHeaders({'Content-Type': 'application/json'}) }

现在,由于它是一个类成员,为了访问它,我们必须使用this. this只是对类上下文的引用,所以我们说给我this类中的成员。

您看到httpOptions被引用的任何地方都将其更改为this.httpOptions

希望您能看到如何以相反的方式进行操作,并将它们定义为类之外的 const。


推荐阅读