4.3

来源:互联网 发布:kmeans算法介绍 编辑:程序博客网 时间:2024/06/07 22:57

Services都是单例的,就是说在一个应用中,每一个Serice对象只会被实例化一次(用$injector服务),主要负责提供一个接口把特定函数需要的方法放在一起,我们就拿上一章见过的$http Service来举例,他就提供了访问底层浏览器的XMLHttpRequest对象的方法,相较于调用底层的XMLHttpRequest对象,$http API使用起来相当的简单。

Angular内建了很多服务供我们日常使用,这些服务对于在复杂应用中建立自己的Services都是相当有用的。

AngularJS让我们可以轻松的创建自己的services,仅仅注册service即可,一旦注册,Angular编译器就可以找到并加载他作为依赖供程序运行时使用,

最常见的创建方法就是用angular.module API 的factory模式

1
2
3
4
5
6
angular.module('myApp.services', [])
  .factory('githubService',function() {
    varserviceInstance = {};
    // 我们的第一个服务
    returnserviceInstance;
  });

当然,我们也可以使用内建的$provide service来创建service。

这个服务并没有做实际的事情,但是他向我们展示了如何去定义一个service。创建一个service就是简单的返回一个函数,这个函数返回一个对象。这个对象是在创建应用实例的时候创建的(记住,这个对象是单例对象)

我们可以在这个纵贯整个应用的单例对象里处理特定的需求,在上面的例子中,我们开始创建了GitHub service,

接下来让我们添加一些有实际意义的代码去调用GitHub的API:

1
2
3
4
5
6
7
8
9
10
11
12
13
angular.module('myApp.services', [])
  .factory('githubService', ['$http',function($http) {
 
    vardoRequest = function(username, path) {
      return$http({
        method:'JSONP',
        url:'https://api.github.com/users/' + username + '/' + path + '?callback=JSON_CALLBACK'
      });
    }
    return{
      events:function(username) {return doRequest(username, 'events'); },
    };
  }]);

我们创建了一个只有一个方法的GitHub Service,events可以获取到给定的GitHub用户最新的GitHub事件,为了把这个服务添加到我们的controller中。我们建立一个controller并加载(或者注入)githubService作为运行时依赖,我们把service的名字作为参数传递给controller 函数(使用中括号[])

1
2
3
app.controller('ServiceController', ['$scope','githubService',
    function($scope, githubService) {
}]);

请注意,这种依赖注入的写法对于js压缩是安全的,我们会在以后的章节中深入导论这件事情。

我们的githubService注入到我们的ServiceController后,我们就可以像使用其他服务(我们前面提到的$http服务)一样的使用githubService了。

我们来修改一下我们的示例代码,对于我们视图中给出的GitHub用户名,调用GitHub API,就像我们在数据绑定第三章节看到的,我们绑定username属性到视图中

1
2
3
4
5
<divng-controller="ServiceController">
  <labelfor="username">Type in a GitHub username</label>
  <inputtype="text"ng-model="username"placeholder="Enter a GitHub username, like auser"/>
  <preng-show="username">{{ events }}</pre>
</div>

现在我们可以监视 $scope.username属性,基于双向数据绑定,只要我们修改了视图,对应的model数据也会修改

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
app.controller('ServiceController', ['$scope','githubService',
    function($scope, githubService) {
    // Watch for changes on the username property.
    // If there is a change, run the function
    $scope.$watch('username',function(newUsername) {
            // uses the $http service to call the GitHub API
            // and returns the resulting promise
      githubService.events(newUsername)
        .success(function(data, status, headers) {
                    // the success function wraps the response in data
                    // so we need to call data.data to fetch the raw data
          $scope.events = data.data;
        })
    });
}]);

因为返回了$http promise(像我们上一章一样),我们可以像直接调用$http service一样的去调用.success方法

 

在这个示例中,我们注意到输入框内容改变前有一些延迟,如果我们不设置延迟,那么我们就会对键入输入框的每一个字符调用GitHub API,这并不是我们想要的,我们可以使用内建的$timeout服务来实现这种延迟。

如果想使用$timeout服务,我们只要简单的把他注入到我们的githubService中就可以了

1
2
3
app.controller('ServiceController', ['$scope','$timeout','githubService',
    function($scope, $timeout, githubService) {
}]);

注意我们要遵守Angular services依赖注入的规范:自定义的service要写在内建的Angular services之后,自定义的service之间是没有先后顺序的。

 

我们现在就可以使用$timeout服务了,在本例中,在输入框内容的改变间隔如果没有超过350毫秒,$timeout service不会发送任何网络请求。换句话说,如果在键盘输入时超过350毫秒,我们就假定用户已经完成输入,我们就可以开始向GitHub发送请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
app.controller('ServiceController', ['$scope','$timeout','githubService',
  function($scope, $timeout, githubService) {
    // The same example as above, plus the $timeout service
    vartimeout;
    $scope.$watch('username',function(newVal) {
      if(newVal) {
        if(timeout) $timeout.cancel(timeout);
        timeout = $timeout(function() {
          githubService.events(newVal)
          .success(function(data, status) {
            $scope.events = data.data;
          });
        },350);
      }
    });
  }]);

从这应用开始,我们只看到了Services是如何把简单的功能整合在一起,Services还可以在多个controllers之间共享数据。比如,如果我们的应用有一个设置页面供用户设置他们的GitHub username,那么我们就要需要把username与其他controllers共享。

这个系列的最后一章我们会讨论路由以及如何在多页面中跳转。

为了在controllers之间共享username,我们需要在service中存储username,记住,在应用的生命周期中Service是一直存在的,所以可以把username安全的存储在这里

1
2
3
4
5
6
7
8
9
10
11
12
13
14
angular.module('myApp.services', [])
  .factory('githubService', ['$http',function($http) {
    vargithubUsername;
    vardoRequest = function(path) {
      return$http({
        method:'JSONP',
        url:'https://api.github.com/users/' + githubUsername + '/' + path + '?callback=JSON_CALLBACK'
      });
    }
    return{
      events:function() {return doRequest('events'); },
      setUsername:function(newUsername) { githubUsername = newUsername; }
    };
  }]);

现在,我们的service中有了setUsername方法,方便我们设置GitHub用户名,在应用的任何controller中,我们都可以调用events()方法,而根本不用操心在scope对象中的username设置是否正确。

 

我们应用里的Services

在我们的应用里,我们需要为3个元素创建对应的服务:audio元素,player元素,nprService。最简单的就是audio service,切记,不要在controller中有任何的操控DOM的行为,如果这么做会污染你的controller并留下潜在的隐患。

在我们的应用中,PlayerController中有一个audio element元素的实例

1
2
3
4
5
app.controller('PlayerController', ['$scope','$http',
  function($scope, $http) {
  varaudio = document.createElement('audio');
  $scope.audio = audio;
  // ...

我们可以建立一个单例audio service,而不是在controller中设置audio元素

1
2
3
4
app.factory('audio', ['$document',function($document) {
  varaudio = $document[0].createElement('audio');
  returnaudio;
}]);

注意:我们使用了另一个内建服务$document服务,这个服务就是window.document元素(所有html页面里javascript的根对象)的引用。

现在,在我们的PlayController中我们可以引用这个audio元素,而不是在controller中建立这个audio元素

1
2
3
app.controller('PlayerController', ['$scope','$http','audio',
  function($scope, $http, audio) {
  $scope.audio = audio;

尽管看起来我们并没有增强代码的功能或者让代码更加清晰,但是如果有一天,PlayerController不再需要audio service了,我们只需要简单删除这个依赖就可以了。到那个时候你就能切身体会到这种代码写法的妙处了!

注意:现在我们可以在其他应用中共享audio service了,因为他并没有绑定特定于本应用的功能

为了看到效果,我们来建立下一个服务: player service,在我们的当前循环中,我们附加了play()和stop()方法到PlayController中。这些方法只跟playing audio有关,所以并没有必要绑定到PlayController,总之,使用PlayController调用player service API来操作播放器,而并不需要知道操作细节是最好不过的了。

让我们来创建player service,我们需要注入我们刚刚创建的还热乎的audio service 到 player service

1
2
3
4
app.factory('player', ['audio',function(audio) {
  varplayer = {};
  returnplayer;
}]);

现在我们可以把原先定义在PlayerController中play()方法挪到player service中了,我们还需要添加stop方法并存储播放器状态。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
app.factory('player', ['audio',function(audio) {
  varplayer = {
    playing:false,
    current:null,
    ready:false,
 
    play:function(program) {
      // If we are playing, stop the current playback
      if(player.playing) player.stop();
      varurl = program.audio[0].format.mp4.$text;// from the npr API
      player.current = program;// Store the current program
      audio.src = url;
      audio.play();// Start playback of the url
      player.playing =true
    },
 
    stop:function() {
      if(player.playing) {
        audio.pause();// stop playback
        // Clear the state of the player
        player.ready = player.playing =false;
        player.current =null;
      }
    }
  };
  returnplayer;
}]);

现在我们已经拥有功能完善的play() and stop()方法,我们不需要使用PlayerController来管理跟播放相关的操作,只需要把控制权交给PlayController里的player service即可

1
2
3
4
app.controller('PlayerController', ['$scope','player',
  function($scope, player) {
  $scope.player = player;
}]);

为了解决这个问题,我们需要使用$rootScope服务(另一个Angular的内建服务)来捕获audio元素的ended事件,我们注入$rootScope服务并创建audio元素的事件监听器

1
2
3
4
5
6
7
8
9
10
11
12
app.factory('player', ['audio','$rootScope',
  function(audio, $rootScope) {
  varplayer = {
    playing:false,
    ready:true,
    // ...
  };
  audio.addEventListener('ended',function() {
    $rootScope.$apply(player.stop());
  });
  returnplayer;
}]);

在这种情况下,为了需要捕获事件而使用了$rootScope service,注意我们调用了$rootScope.$apply()。 因为ended事件会触发外围Angular event loop.我们会在后续的文章中讨论event loop。

 

最后,我们可以获取当前播放节目的详细信息,比如,我们创建一个方法获取当前事件和当前audio的播放间隔(我们会用这个参数显示当前的播放进度)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
app.factory('player', ['audio','$rootScope',
  function(audio, $rootScope) {
  varplayer = {
    playing:false,
    // ...
    currentTime:function() {
      returnaudio.currentTime;
    },
    currentDuration:function() {
      returnparseInt(audio.duration);
    }
  }
  };
  returnplayer;
}]);

在audio元素中存在timeupdate事件,我们可以根据这个事件更新播放进度

1
2
3
4
5
6
audio.addEventListener('timeupdate',function(evt) {
    $rootScope.$apply(function() {
      player.progress = player.currentTime();
      player.progress_percent = player.progress / player.currentDuration();
    });
  });

最后,我们一个添加canplay事件来表示视图中的audio是否准备就绪

1
2
3
4
5
6
7
8
9
10
11
12
13
14
app.factory('player', ['audio','$rootScope',
  function(audio, $rootScope) {
  varplayer = {
    playing:false,
    ready:false,
    // ...
  }
  audio.addEventListener('canplay',function(evt) {
    $rootScope.$apply(function() {
      player.ready =true;
    });
  });
  returnplayer;
}]);

现在,我们有了player service,我们需要操作nprLink directive 来让播放器 ’play’,而不是用$scope(注意,这么做是可选的,我们也可以在PlayerController中创建play()和stop()方法)

在directive中,我们需要引用本地scope的player,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
app.directive('nprLink',function() {
  return{
    restrict:'EA',
    require: ['^ngModel'],
    replace:true,
    scope: {
      ngModel:'=',
      player:'='
    },
    templateUrl:'/code/views/nprListItem',
    link:function(scope, ele, attr) {
      scope.duration = scope.ngModel.audio[0].duration.$text;
    }
  }
});

现在,为了跟我们已有的模板整合,我们需要更新 index.html的npr-link调用方式

1
<npr-linkng-model="program"player="player"></npr-link>

在视图界面,我们调用play.play(ngModel),而不是play(ngModel).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<divclass="nprLink row"player="player"ng-click="player.play(ngModel)">
  <spanclass="name large-8 columns">
    <buttonclass="large-2 small-2 playButton columns"ng-click="ngModel.play(ngModel)"><divclass="triangle"></div></button>
    <divclass="large-10 small-10 columns">
      <divclass="row">
        <spanclass="large-12">{{ ngModel.title.$text }}</span>
      </div>
      <divclass="row">
        <divclass="small-1 columns"></div>
        <divclass="small-2 columns push-8"><ahref="{{ ngModel.link[0].$text }}">Link</a></div>
      </div>
    </div>
  </span>
</div>

逻辑上,我们需要添加播放器视图到总体视图上,因为我们可以封装player数据和状态。查看playerView directive 和 template

我们来创建最后一个service,nprService,这个service很像 githubService,我们用$http service来获取NPR的最新节目

1
2
3
4
5
6
7
8
9
10
11
12
app.factory('nprService', ['$http',function($http) {
    vardoRequest = function(apiKey) {
      return$http({
        method:'JSONP',
        url: nprUrl +'&apiKey=' + apiKey + '&callback=JSON_CALLBACK'
      });
    }
 
    return{
      programs:function(apiKey) {return doRequest(apiKey); }
    };
  }]);

在PlayerController,我们调用nprService的programs()(调用$http service)

1
2
3
4
5
6
7
8
app.controller('PlayerController', ['$scope','nprService','player',
  function($scope, nprService, player) {
  $scope.player = player;
  nprService.programs(apiKey)
    .success(function(data, status) {
      $scope.programs = data.list.story;
    });
}]);

我们建议使用promises来简化API,但是为了展示的目的,我们在下一个post会简单介绍promises。

当PlayerController初始化后,我们的nprService会获取最新节目,这样我们在nprService service中就成功封装了获取NPR节目的功能。另外,我们添加RelatedController在侧边栏显示当前播放节目的相关内容。当我们的player service中获取到最新节目时,我们将$watc这个player.current属性并显示跟这个属性相关的内容。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
app.controller('RelatedController', ['$scope','player',
  function($scope, player) {
  $scope.player = player;
 
  $scope.$watch('player.current',function(program) {
    if(program) {
      $scope.related = [];
      angular.forEach(program.relatedLink,function(link) {
        $scope.related.push({
          link: link.link[0].$text,
          caption: link.caption.$text
        });
      });
    }
  });
}]);

在 HTML 代码中, we just reference the related links like we did with our NPR programs, using the ng-repeat directive:

1
2
3
4
5
6
<divclass="large-4 small-4 columns"ng-controller="RelatedController">
  <h2>Related content</h2>
  <ulid="related">
    <ling-repeat="s in related"><ahref="{{ s.link }}">{{ s.caption }}</a></li>
  </ul>
</div>

只要player.current内容改变,显示的相关内容也会改变。

 

0 0
原创粉丝点击