angular - 如何在第三个组件类中扩展两个 Angular 类组件?
问题描述
我有一些功能我有两个单独的组件类,例如类组件 A 和类组件 B。我想扩展类组件 C 中的那些。
我听说我可以在 Angular typescript 中从 Mixin 获得帮助,但不确定如何在 Component 类中使用它。如果有任何方法可以在角度上实现相同的效果,那将会很有帮助。
我还检查了这里提到的示例: https ://stackblitz.com/edit/mixin-example
我也试过 applyMixins 如下,但无法在 Class 组件中解决。
class A {
start() {
console.log('Vehicle Started');
}
}
class B {
end() {
console.log('Vehicle stopped');
}
}
class C implements A, B {
end(): void {
throw new Error("Method not implemented.");
}
start(): void {
throw new Error("Method not implemented.");
}
}
applyMixins(C, [A, B])
解决方案
我不太确定你为什么要这样做,但我设法让它工作: https ://stackblitz.com/edit/angular-typescript-mixins
简而言之,我将函数applyMixins包装到一个文件中
export function applyMixins(derivedCtor: any, baseCtors: any[]) {
baseCtors.forEach(baseCtor => {
Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => {
if (name !== 'constructor') {
derivedCtor.prototype[name] = baseCtor.prototype[name];
}
});
});
}
后来在组件C中,我实现了组件A和B,最后在构造函数中调用了该函数:
export class CComponent implements AComponent, BComponent {
end(): void {
throw new Error("Method not implemented.");
}
start(): void {
throw new Error("Method not implemented.");
}
constructor() {
applyMixins(CComponent,[AComponent,BComponent])
}
}
推荐阅读
- asp.net - Visual Studio 2019 - 不兼容 找不到此项目类型所基于的应用程序
- c# - 如何在 C# 中提交 php 表单
- c# - SHA1CryptoServiceProvider 与 HMACSHA1 有什么区别
- asp.net - “Windows 身份验证”和“直通身份验证”是一回事吗?
- java - Tomcat一段时间后没有响应
- c++ - Qt 5.8 或更高版本如何使用 ROS?
- php - 2019 PHPMailer 6.07 / PHP Scrip 如何发送电子邮件工作示例
- git - 当 GitHub 上的 master 分支更新时,刷新 ubuntu 服务器上的 repo。我怎样才能做到这一点?
- c# - 使用 ASP.NET Core MVC 控制器将 RestSharp POST 请求连接到 Web API 的问题
- javascript - 我想让球在画布底部消失时以新的随机速度、颜色和位置重绘