Getter 用于 Angular 服务 属性 而不是将其存储在组件中

Getter for Angular service property instead of storing it in component

我有一个组件 MainComponent,它需要访问存储在 MainService 中的 User 对象。

与其将 User 对象同时存储在 MainComponentMainService 中,不如在 MainComponent 中设置 getter 被认为是不好的做法, 哪个 returns 来自 MainService 的实例?这样,User 对象将只存储在一个地方。

export class MainComponent implements OnInit {
   get user() {
      return this.mainService.user;
   }
@Injectable()
export class MainService {
    User!: IUser;

深入研究了 Angular DI 文档 (https://angular.io/guide/dependency-injection-in-action),我发现这实际上是他们用于 HeroCacheService 的确切方法:

@Component({
  selector: 'app-hero-bio',
  template: `
    <h4>{{hero.name}}</h4>
    <ng-content></ng-content>
    <textarea cols="25" [(ngModel)]="hero.description"></textarea>`,
  providers: [HeroCacheService]
})

export class HeroBioComponent implements OnInit  {
  @Input() heroId = 0;

  constructor(private heroCache: HeroCacheService) { }

  ngOnInit() { this.heroCache.fetchCachedHero(this.heroId); }

  // This part here answered my question!
  get hero() { return this.heroCache.hero; }
}