# $provide对象的provider、factory、service方法

## 定义服务 $provider

* 服务本身是一个任意的对象。
* ng 提供服务的过程涉及它的依赖注入机制。
* angular 是用$provider对象来实现自动依赖注入机制，注入机制通过调用一个 provider 的 $get() 方法，把得到的对象作为参数进行相关调用
* $provider提供很多很定义服务的方法,这些简便的方法还直接被module所引用

## 三种定义服务方式

* $provider.provider&#x20;
* $provider.factory
  * factory 方法直接把一个函数当成是一个对象的 $get() 方法
  * @see module.factory
  * 返回的内容可以是任何类型&#x20;
* $provider.service
  * 和factory类似，但返回的东⻄西必须是对象
  * @see module.service

**例子：**

index.html

```markup
 <div ng-app="myApp">

        <div ng-controller="firstController">
            {{name}}
        </div>

    </div>

<script src="//cdn.bootcss.com/angular.js/1.4.8/angular.js"></script>
<script type="text/javascript" src="app/index.js"></script>
```

app/index.js

```javascript
var myApp = angular.module('myApp',[],function($provide){

    // 自定义服务
    $provide.provider('CustomService',function(){

        this.$get = function(){
            return {
                message : 'CustomService Message'
            }
        }
    });

    // 自定义工厂
    $provide.factory('CustomFactory',function(){
        return [1,2,3,4,5,6,7];
    });

    // 自定义服务
    $provide.service('CustomService2',function(){
        return {
                message : 'CustomService Message2'
            }
    })

});

myApp.controller('firstController',function($scope, CustomFactory, CustomService, CustomService2){
    $scope.name = '张三';

    console.log(CustomFactory);

    console.log(CustomService);

    console.log(CustomService2);

});
```

注意：也可以通过以下方式定义服务

```javascript
var app = angular.module('myApp', []);
app.service();
app.factory();
```

**效果**

![](/files/-LfnTGBebmjgYgwTgJkW)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://xiaoxiami.gitbook.io/angularjs/provide_ding_yi_fu_wu.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
