Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angularjs 通过@injectable和es6模块提供角度服务_Angularjs_Angular_Ecmascript 6_Singleton_Injectable - Fatal编程技术网

Angularjs 通过@injectable和es6模块提供角度服务

Angularjs 通过@injectable和es6模块提供角度服务,angularjs,angular,ecmascript-6,singleton,injectable,Angularjs,Angular,Ecmascript 6,Singleton,Injectable,在angular中,我们需要创建@Injactable服务类并将其提供给我们的项目 理论上,我们也可以导入执行为单例服务的es6模块 除了这不是“角度法”,为什么这种方法不那么普遍 角度法 import { Injectable } from '@angular/core'; @Injectable() export class fo { getFo():{ } } es6路 const bla = [] const fo() => {return bla}

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

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

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

角度法

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

    const bla = []
    const fo() => {return bla}
    export {
        fo
    }
@Injectable()
仅在您的服务注入其他服务时才有必要

例如:

@Injectable()
export class fo {
   constructor(private myOtherService: MyOtherService){}
}
除此之外,您是对的,返回
常量几乎是一样的。但是,正如您所理解的,添加注释和逻辑是一种很好的做法

资料来源:

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


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

为什么@Injectable()?

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


来源:

“除此之外,你是对的,这实际上是同一件事”绝对不是。@zeroflagL是的,这是一个夸张的陈述,我很遗憾我写了:D,但因为OP只是使用服务返回一个
常量
;对于这种用法,我想他们实际上是一样的,先生。当然,我假设OPs
getFo()
方法返回与第二个示例相同的
const
。您是对的,在这个特定的示例中,这可能无关紧要,但这不是一个真实的示例。问题中的示例只是为了说明这一点,答案不应局限于此。@zeroflagL我将尝试提供有关此主题的更多详细信息,但如您所知,这将要求我还解释Angular等的依赖注入系统。我试图给我的上一次编辑提供一个合理的资源来阅读。我欣赏你的批评:-)你的两个例子毫无共同之处。