Angular 组件继承和继承订阅

nob*_*alG 5 inheritance subscription publish-subscribe angular

下面是一个组件,我将在其他各种组件中扩展它以重用一些代码..

import { Component } from '@angular/core';

@Component ({
   selector: 'my-app',
   template: ` <div>
      <h1>{{appTitle}}</h1>
      <div>To Tutorials Point</div>
   </div> `,
})

export class AppComponent {
   appTitle: string = 'Welcome';
   ngOnInit(){
      this.registerSomeSubscriptions();
   }
   registerSomeSubscriptions(){
      this.subscribeSomething.subscribe((data)=>{
         performSomeAction();
      })
   }


}
Run Code Online (Sandbox Code Playgroud)

我可以像下面这样扩展它

 import { Component } from '@angular/core';

@Component ({
   selector: 'my-app',
   template: ` <div>
      <h1>{{appTitle}}</h1>
      <div>To Tutorials Point</div>
   </div> `,
})

export class ChildComponent extends AppComponent {
   
}
Run Code Online (Sandbox Code Playgroud)

虽然我知道组件的公共成员将在子组件中可用。

我的问题

  1. 我是否仍然必须为这两个组件使用单独的 html 文件,还是使用一些代码样式或解决问题的技术来重用相同的 html 模板以及通过我不知道的某些技术的一些特定于孩子的实现。

New*_*hua 2

子组件可以使用与父组件相同的 html 模板,也可以拥有自己的 html 文件,在这种情况下,将不会使用父组件的 html。

如果您想在子组件中使用父组件的 html 并进行一些修改,您可以重用父组件而不是继承它。

  • 使您的父组件成为可重用组件
  • 在子/功能组件的模板中,使用其选择器添加父组件
    // add something specific to child/feature component here
    <app-reusable-component></app-reusable-component>
    // add something specific to child/feature component here
Run Code Online (Sandbox Code Playgroud)

可重用组件的 html 将与您在功能组件的 html 中添加的其他 html 一起使用。

  • 要在可重用组件和功能组件之间传递数据,请使用组件交互 -InputOutput

  • Input- 通过输入绑定将数据从功能组件传递到可重用组件

reusable-component.ts:
export class ReusableComponent implements OnInit {
   @Input() dataIn: Observable<object>;
   ngOnInit() {
     dataIn.subscribe(data => {
       // display data
     });
   }
}

feature-component.html:
...
<app-reusable-component [dataIn]="dataToDisplay$"></app-reusable-component>
...

feature-component.ts:
export class FeatureComponent implements OnInit {
  public dataToDisplay$: Observable<object>;
  ngOnInit() {
    this.dataToDisplay$ = this.http.get(url);
  }
}
Run Code Online (Sandbox Code Playgroud)
  • Output- 将数据/事件从可重用组件发送到功能组件
reusable-component.ts:
export class ReusableComponent implements OnInit {
   @Input() dataIn: Observable<object>;
   @Output() eventOut: EventEmitter<object> = new EventEmitter<object>();
   ngOnInit() {
     dataIn.subscribe(data => {
       // display data
     });
   }
   userInput(value) {
      this.eventOut.emit(value);
   }
}

feature-component.html:
...
<app-reusable-component [dataIn]="dataToDisplay$" (eventOut) ="handleUserData($event)"></app-reusable-component>
...

feature-component.ts:
export class FeatureComponent implements OnInit {
  public dataToDisplay$: Observable<object>;
  ngOnInit() {
    this.dataToDisplay$ = this.http.get(url);
  }
  handleUserData(value) {
    this.http.post(url, value);
  }
}
Run Code Online (Sandbox Code Playgroud)

通过这种方法,您可以在所有子/功能组件中重用父组件的模板,并且您将能够在子/功能组件中添加其他 html 内容并在它们之间传递数据。