som*_*020 5 javascript composition typescript angular angular6
我在Angular中有一个结构如下的模块:
moduleName
componentA
componentB
Run Code Online (Sandbox Code Playgroud)
现在componentA和componentB它们非常相似,因为它们共享一些属性和方法,例如:
protected available: boolean = true;
Run Code Online (Sandbox Code Playgroud)
因为不想重复自己,所以我创建了一个基类,用于存储所有这些内容:
export abstract class BaseComponent {
protected available: boolean = true;
}
Run Code Online (Sandbox Code Playgroud)
并且两个控制器都从该类继承:
import { BaseComponent } from '../base.component';
export class ComponentA extends BaseComponent implements OnInit {
constructor() {
super();
}
ngOnInit() {
console.log(this.available);
}
}
Run Code Online (Sandbox Code Playgroud)
这样很好。但是,当我研究这种灵魂时,很多人都在说:
不要使用继承,在这种情况下请使用合成。
好的,但是我该如何使用合成呢?与当前解决方案相比,收益真的那么大吗?
非常感谢您的宝贵时间。
要以 angular 组合对象,您需要在类中引用该对象,该对象共享数据和功能。为此,您需要使用 Angular 服务,并将它们注入您的类,并且每个组件应该有 1 个服务实例。
ng g s my-service,providedIn: 'root'从您的服务注释中删除(我们希望为每个组件提供实例)public available: boolean = true;到服务provide通过组件的服务,在@Component你的组件的配置中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) {
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2320 次 |
| 最近记录: |