2017-03-04 61 views
1

Q1。我有一个公共实用程序类与一些实用程序/帮助器方法(没有获取/发布请求)。首先我要问的是,它应该是一个简单的课程还是一个@Injectable课程。因为两者都可以进口任何组件类这样Angular 2构造函数注入vs直接访问

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

Injectable() 
export class Utils { 
} 

OR

export class Utils { 
} 

Q2后使用。如果是注射的话,我不得不进口这在我的组件类,在构造函数注入,并且必须在供应商阵列添加,然后我就可以使用注射类/服务的任何方法像

import { Utils } from './../shared/utils'; 

@Component({ 
    moduleId: module.id, 
    selector: 'abc', 
    templateUrl: './abc.component.html', 
    providers: [Utils] 
}) 

export class DemoComponent implements OnInit { 

    constructor(private _u: Utils) { } 

    ngOnInit(): void { 
     this._u.someMethod(); 
    } 
} 

但这旁我可以直接访问而无需构造函数注入和服务方法,而不必在供应商增加,这就好比

import { Utils } from './../shared/utils'; 

@Component({ 
    moduleId: module.id, 
    selector: 'abc', 
    templateUrl: './abc.component.html' 
}) 

export class DemoComponent implements OnInit { 

    constructor() { } 

    ngOnInit(): void { 
     Utils.someMethod(); 
    } 
} 

显示我想知道哪一个更好,推荐的方法一小段路?

回答

1

当你在构造函数中使用它,

  1. 您使用该服务的一个单独的实例在您的组件。
  2. 当用作Injectable()时,应该在供应商模块的数组内部声明。

    constructor(private _u: Utils) { } 
         ngOnInit(): void { 
           this._u.someMethod(); 
         } 
    
    //private - _u => is specific inside this component 
    

在直接接入的情况下,资源被使用,因为它是这可能会给下列问题

  1. 内存泄漏
  2. 少重用
  3. 在观测的情况下,直到一个observable被取消订阅,你不能再订阅它。
+0

因此,每个帮助器类应该由构造器注入使用?如何在组件中单独实现服务,因为服务始终是单例? –

+0

不完全是,但在主要情况下是的,它应该被注射。 – Aravind

+0

即使没有可观察到的东西,只是平坦的方法? –

1

Q1。 @Injectable()如果Utils不依赖于任何其他服务是不需要的,但如果这样做,你必须使用@Injectable()装饰:

// 1 case 

    @Injectable() // <--- required 
    export class Utils { 
     constructor(private _otherService : OtherService){} 
    } 


    // 2 case 
    @Injectable() // <--- not required 
    export class Utils { 
     constructor(){} 
    } 

在您需要的组件的供应商阵列中添加的服务这两种情况。 Q2302。使用第一种方法,因为它可以通过传递MockUtils服务来轻松测试组件。