如何扩展一个类,其构造函数的参数类型为" Title" - @ angular / platform-b​​rowser类型参数

时间:2017-08-30 12:51:04

标签: angular typescript

我想获取/设置网页标题,我这样做:

  

GetTitle.ts

import { Title }     from '@angular/platform-browser';
......
export class GetTitle {

    public constructor(private titleService: Title ) { }

    public setTitle( newTitle: string) {
      this.titleService.setTitle( newTitle );
    }
}  

但是!如果我想制作一个新的子类,将会继承这个子类 如何在子TestGetTitleClass中编写构造函数?
如何制作父GetTitle类的实例?

  

TestGetTitleClass.ts

import {GetTitle} from "../path..";
let getTitleInstance : GetTitle = new GetTitle( ??? ?? );

export class TestGetTitleClass extends GetTitle{
   constructor(){
       super( ???? );
   }
}

2 个答案:

答案 0 :(得分:4)

我将在此处发布一些代码,其中包含我之前完成的工作示例,这样您就可以了解其工作原理:

ComponentViewRightMode类:此类允许我通过ApplicationService了解给定URL的当前用户权限(因此Router依赖项)。

export class ComponentViewRightMode {
    private _routerReference: Router;
    private _applicationsServiceReference: ApplicationsService;
    viewRight: string;

    constructor(
        router: Router,
        applicationsService: ApplicationsService
    ) {
        this._routerReference = router;
        this._applicationsServiceReference = applicationsService;
        this.getCurrentUserViewRight();
    }

    getCurrentUserViewRight() {
        this.viewRight = this._applicationsServiceReference.currentViewReadMode(this._routerReference.url);
    }
}

StockComponent类:以下是使用的语法。注意我需要我的组件使用super()注入依赖项。

export class StockComponent extends ComponentViewRightMode implements OnInit {

    constructor(
      private router: Router,
      private applicationsService: ApplicationsService,
      ...
    ) {
      super(router, applicationsService);
    } 
}

基本上,我需要许多组件可以访问viewRight类中的ComponentViewRightMode属性。由于该属性直接填充在我的顶级类的构造函数中,因此扩展该类的所有组件都可以异步访问它(因为我的服务)。

因此,我能够按预期使用我的属性我的模板:

StockComponent模板:

<div class="stock-actions">
  >>>>> This is where I use the viewRight property <<<<<
  <button [disabled]="viewRight !== 'Write'" md-raised-button (click)="navigateTo('someURL')">
    {{'STOCK.EQUIPMENT_ADD'|translate}}
  </button>
  ...
</div>

希望这个有效的例子可以帮助你

答案 1 :(得分:0)

我建议尝试这种方式

你的(你可以定义一个抽象类)

export abstract class Titler {
  constructor(protected title: string) {}
}

protected 属性意味着该方法或属性只能在类或扩展它的任何类内部访问,而不能从外部访问。

您的孩子

export class TestTitler extends Titler {
  constructor(protected title: string) {
     super(title);
  }
}

您的 SuperChild 类(仅作为示例)

export class SuperChildTestTitler extends TestTitler {
  anyWayDoTitle(){
    return this.title;
  }
}