问题
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",
};
}
In the constructor
of the app-component
I have declared the child instance as follows:
constructor(private child_instance:ChildService){}
When printing child_instance
in the browser console I get:
ParentService {word: {…}}
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: {…}}
How can I acomplish this?
回答1:
After the clarification of @Satish Pai I have created a work around:
In the ParentService
class:
/* Some code here... */
export class ParentService {
constructor() { }
word:Lang = {
"ES":"ESP",
"EN":"ENG",
}
/* Some code here... */
}
In the ChildService
class:
/* Some code here... */
export class ChildService{
constructor(){
var gParent:ParentService = new ParentService();
var gkeys = Object.keys(gParent);
for(var i = 0; i < gkeys.length; i++){
this[gkeys[i]] = gParent[gkeys[i]];
}
}
/* Some code here... */
}
WARNING: this will copy the whole ParentClass
into the ChildClass
(even functions)
Suggestion: You can aply some regex
over gkeys
to only copy certain functions
or variables
.
回答2:
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: {…}}
}
}
来源:https://stackoverflow.com/questions/60100165/angular-6-and-typescript-child-class-extends-from-parent-class-and-banish-child