Angular 6 和 typescript 子类从父类扩展并消除子变量 [英] Angular 6 and typescript child class extends from parent class and banish child variables

查看:22
本文介绍了Angular 6 和 typescript 子类从父类扩展并消除子变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 ParentServiceabstract class 和它的 child class ChildService 如下:

I have an abstract class called ParentService and its child class ChildService as follows:

ParentService

import { Injectable } from '@angular/core';
import { MyModel} from './mymodel-model.service';
@Injectable({
  providedIn: 'root'
})
export abstract class ParentService {
  constructor() { }
  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",
  };
}

app-componentconstructor 中,我声明了子实例如下:

In the constructor of the app-component I have declared the child instance as follows:

constructor(private child_instance:ChildService){}

在浏览器控制台中打印 child_instance 时,我得到:

When printing child_instance in the browser console I get:

 ParentService {word: {…}}

没有 extends ParentService 我得到:

 ChildService {word2: {…}}

但我需要在同一个类中有两个变量:

But I need to have both variables in the same class:

ChildService {word: {…},word2: {…}}
//or
ParentService {word: {…},word2: {…}}

我怎样才能做到这一点?

How can I acomplish this?

推荐答案

你需要在你的 child.service 构造函数中调用 super().

you need to call the super() inside your child.service constructor.

export class ParentService {
  constructor() { }
  word = { 
    "AA":"AA",
    "BB":"BB",
  }
}

export class ChildService extends ParentService {
  word2 = {
    "AA":"AA2",
    "BB":"BB2",
  };

  constructor() {
    super();
    console.log(this); // prints ChildService {word: {…}, word2: {…}}
 }
}

这篇关于Angular 6 和 typescript 子类从父类扩展并消除子变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆