Angular 2构造函数注入与直接访问 [英] Angular 2 constructor injection vs direct access

查看:75
本文介绍了Angular 2构造函数注入与直接访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Q1。我有一个带有一些实用程序/帮助程序方法的通用实用程序类(没有获取/发布请求)。我首先要问的是,它应该是简单的类还是 @Injectable 类。因为两者都可以在导入这样的任何组件类之后使用

Q1. I have a common utility class with some utility/helper methods (no get/post request). First thing I have to ask is that whether it should be a simple class or an @Injectable class. Because both can be used after importing in any component class like this

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

Injectable()
export class Utils {
}

OR

export class Utils {
}

第二季度。如果它是可注入的,那么我必须将其导入到我的组件类中,注入到构造函数中,并且必须添加providers数组,然后我可以使用注入的类/服务的任何方法,例如

Q2. If it's injectable then I have to import this in my component class, inject in the constructor, and must have to add in providers array then I can use any method of the injected class/service like

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();
    }
}

但是除此之外,我可以直接访问服务方法而无需构造函数注入,而无需添加提供程序,这是一个简短的方法,例如

But beside this I can directly access the service methods without constructor injection and without having to add in providers, which is a short way like

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();
    }
}

所以我想知道哪个更好,建议

So I wanted to know which one is better and recommended approach?

推荐答案

在构造函数中使用它时,

When you are using it in constructor,


  1. 您在整个组件中使用服务的单独实例。

  2. 用作Injectable()时,应在提供者内部声明该模块的数组。

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

 //private - _u => is specific inside this component


如果是直接访问,资源将按原样使用,这可能会导致以下问题

In case of direct access, the resources are used as it is which might create following problems


  1. 内存泄漏

  2. 较少可重用性

  3. 对于可观察性,在取消可观察性之前,您无法再次订阅。

这篇关于Angular 2构造函数注入与直接访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆