2017-02-25 73 views
3

我有成分B,C,d,从A类继承角2:注射服务手动

我想用A类服务,但我不知道怎么把它注射,无需进它来自它的孩子。

我想什么是正常的注射: constructor(pageName: string = null, translate: TranslateService) { 但是当我做super()建设A级,是因为我没有提供第二个参数抛出一个错误。

有没有办法使用Angular2注入父类?

角版本我不得不使用方法是:2.2.1

编辑:

一些示例情况: 我有很多的网页,每个人都可以显示一个加载器。相反,从每一个页面,每次注射的装载机和管理装载机的,我想要做的:

export class BaseComponent { 
    constructor(private loader: LoadingService) {} 

    showLoading() { 
     this.loader.show(); 
    } 
} 

然后从组件本身继承:

@Component({ 
    selector: "page-login", 
    providers: [UsersService], 
    templateUrl: "login.html" 
}) 
export class LoginPage extends BaseComponent { 
    constructor(private usersService: UsersService) { 
     super(); 
    } 
} 

现在LoginPage有一个方法showLoading从它是父母。

+0

这可能适合你:http://stackoverflow.com/questions/37117698/angular2-use-imported-libs-from-base-class/37117732#37117732。 – pixelbits

+0

@pixelbits谢谢,刚刚发现了另一个解决方法。我将TranslateService注入到应用程序中,然后将该实例保存在一个全局变量中,该变量是我数据存储的一部分(我知道,不应该这样做),并且它工作得很好。 – Amit

+0

我不会称这是一个很好的模式。而你目前的例子并不反映这个问题。没有TranslateService。相反,有showLoading方法,我没有看到它应该在那里的原因。 – estus

回答

8

您可以通过使用服务定位器服务来解决此问题。这很容易让你得到任何服务,并在你的父类中使用它,而无需通过他们的孩子注入它们(因为这可能是一个痛苦)。

因此,要利用这一点,创建一个简单的类locator.service.ts

import {Injector} from "@angular/core"; 

export class ServiceLocator { 
    static injector: Injector; 
} 

导入这项服务在您的app.module.ts

import {ServiceLocator} from './locater.service.ts'; 

然后在你的模块文件的构造函数(app.module.ts?),初始化这个东西,所以你可以在任何地方使用它:

export class AppModule { 
    constructor(private injector: Injector){ // Create global Service Injector. 
     ServiceLocator.injector = this.injector; 
    } 
} 

现在,用它在你的超类(你BaseComponent),只需导入服务定位

import {ServiceLocator} from './locater.service.ts'; 

,并用它喜欢:

export class BaseComponent { 
    constructor() { 
     this.loader = ServiceLocator.injector.get(LoadingService) 
    } 

    showLoading() { 
     this.loader.show(); 
    } 
} 

现在你已经注入您服务在一个可扩展的父项中,并且它可以在你的子组件中使用,而不必在super()中传递它。

+1

但请不要忘记,服务定位器被认为是反模式,虽然有时是有用的。 –

+0

当你有几个使用服务的子类(不是特定的组件,我的意思是数据模型)时,这很有用。您不需要在这些类的构造函数中拥有服务参数。多谢! – coding4fun