1

在 Angular 中,我们需要创建 @Injactable 服务类并将其提供给我们的项目。

理论上,我们也可以导入作为单例服务执行的 es6 模块。

除了这不是“角度方式”之外,为什么这种方法不那么普遍?

角度方式

import { Injectable } from '@angular/core';
@Injectable()
export class fo {
   getFo():{
   }
}

es6方式

    const bla = []
    const fo() => {return bla}
    export {
        fo
    }
4

1 回答 1

2

@Injectable()仅当您的服务正在注入其他服务时才需要。

例子:

@Injectable()
export class fo {
   constructor(private myOtherService: MyOtherService){}
}

除此之外,您是对的,返回 a 几乎是一样的const。但是,如您所见,添加注释和逻辑是一种很好的做法。

来源:https ://angular.io/docs/ts/latest/cookbook/dependency-injection.html#!#-injectable-

从技术上讲,@Injectable() 装饰器仅对具有自己的依赖项的服务类是必需的


简而言之,我们用于@Injectables获取/设置数据并在组件之间以及整个应用程序之间进行通信,这些组件是我们的依赖注入树的一部分。关于为什么应该使用@Injectable().

为什么是@Injectable()?

@Injectable()将一个类标记为可用于注入器进行实例化。一般来说,注入器在尝试实例化未标记为的类时会报告错误@Injectable()

来源:https: //angular.io/docs/ts/latest/guide/dependency-injection.html#! #why- -injectable- -

于 2017-04-05T06:59:22.173 回答