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

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

问题描述

我有一个名为 ParentService 抽象类和其子类 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-component constructor 中,我声明了以下子实例:

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: {…}}

在没有扩展ParentService 的情况下,我得到了:

Without the extends ParentService I got:

 ChildService {word2: {…}}

但是我需要在同一个类中同时包含两个变量:

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

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

我该如何完成呢?

推荐答案

您需要在 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天全站免登陆