Typescript子类变量从父变量返回未定义

时间:2020-02-06 15:57:23

标签: angular typescript

我已经尝试过here发布的解决方案和建议(可能重复了),但可以找出我所缺少的内容。

我有一个名为abstract class的{​​{1}}和它的ParentService child class,如下所示:

ChildService

ParentService

import { Injectable } from '@angular/core'; import { MyModel} from './mymodel-model.service'; @Injectable({ providedIn: 'root' }) export abstract class ParentService { constructor() { } //the other post suggeted to add 'static' but it doesn´t solve it public static word:MyModel = { "AA":"AA", "BB":"BB", } }

ChildService

从我的import { Injectable } from '@angular/core'; import { MyModel} from './mymodel-model.service'; import { ParentService } from './parent.service'; @Injectable({ providedIn: 'root' }) export class ChildService extends ParentService { word2:MyModel = { "AA":"AA2", "BB":"BB2", }; } 中可以访问在html-component中定义的variables,但是当尝试从其Childservice中读取variables时,我得到了{{1} }

ParentService

2 个答案:

答案 0 :(得分:0)

如果您需要将ParentService.word设为静态,请在子级中添加吸气剂,以达到目的:

import { Injectable } from '@angular/core';
import { MyModel} from './mymodel-model.service';
import { ParentService } from './parent.service';
@Injectable({
  providedIn: 'root'
})
export class ChildService extends ParentService {
  word2:MyModel = {
    "AA":"AA2",
    "BB":"BB2",
  };
  get word3(){
    return ParentService.word;
  }}
}

{{ child_instance.word3.AA }}现在应该返回'AA'

答案 1 :(得分:0)

好吧,经过一番挖掘,我发现Angular(或至少是我的6+版本)没有从import那里“ include / propertiesextended class开始,更多信息here

因此解决方案是从一开始(variables)就将function的{​​{1}} / parentchild复制到contructor。信息here