javascript - 在 Angular 6 中的组件之间共享逻辑时如何使用组合而不是继承?

标签 javascript angular typescript angular6 composition

我在 Angular 中有一个结构如下的模块:

moduleName
    componentA
    componentB

现在 componentAcomponentB 非常相似,因为它们共享一些属性和方法,例如:

protected available: boolean = true;

因为我不想重复,所以我创建了一个基类,它存储了所有这些:

export abstract class BaseComponent {
    protected available: boolean = true;
}

并且两个 Controller 都继承自该类:

import { BaseComponent } from '../base.component';

export class ComponentA extends BaseComponent implements OnInit {
    constructor() {
        super();
    }

    ngOnInit() {
        console.log(this.available);
    }
}

这很好用。然而,当我研究这个灵魂时,很多人都在说:

Don't use inheritance, use composition in this case.

好的,但是我怎样才能使用组合呢?与当前解决方案相比, yield 真的那么大吗?

非常感谢您的宝贵时间。

最佳答案

为了以 Angular 组合对象,您需要在您的类中引用该对象,它共享数据和功能。为此,您需要使用 Angular 服务,并将它们注入(inject)您的类,并且每个组件应该有 1 个服务实例。

  1. 通过运行 ng g s my-service 创建一个新服务,从您的服务注释中删除 providedIn: 'root'(我们希望为每个组件提供实例)<
  2. 添加public available: boolean = true;到服务
  3. 通过组件提供服务,在组件的@Component配置中
  4. 在您的两个组件构造函数中注入(inject)服务,constructor(private myService:MyService)

现在你有了一个保留数据和功能的组合

@Component({
  selector: 'app',
  templateUrl: './app.my-component.html',
  styleUrls: ['./app.my-component.css'],
  providers: [MyService]
})
export class MyComponent {
  constructor(private myService: MyService) {
  }
}

关于javascript - 在 Angular 6 中的组件之间共享逻辑时如何使用组合而不是继承?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52333542/

相关文章:

javascript - 如何从javascript中的行中获取唯一数据

javascript - Angular 的循环模板可以通过枚举循环吗?

arrays - angular 5,如何从 promise 中返回数组?

angular - 语法错误: Cannot use import statement outside a module using @ionic-native/health in Angular/Nx/jest app

typescript - 如何避免在 TS 三重斜杠指令中进行难看的导入

typescript - 防止构造方法拼写错误

javascript - 图像幻灯片和复习

javascript - react : Warning: Can't perform a React state update on an unmounted component

Angular 6 - 错误类型错误 : Cannot read property 'value' of undefined

javascript - Node.js 服务器不工作