美文网首页我爱编程
Angular自定义服务&&路由

Angular自定义服务&&路由

作者: 西巴撸 | 来源:发表于2017-04-16 09:14 被阅读117次

什么是跨域

  • 不同域名之间进行数据访问,默认情况下是不允许的。

是谁导致了跨域

  • 是浏览器导致了跨域,为了数据的安全。

怎样解决跨域

  • 使用插件
  • JSONP

Ajax和jsonp是同一个东西么

  • Ajax的核心是通过XmlHttpRequest获取非本页内容
  • 而jsonp的核心则是动态添加<script>标签来调用服务器提供的js脚本。

JSONP的实现原理

  • **示例代码 : **
<script>
    function fn(res) {
        console.log('callback' + '---------' + res);
    }
</script>
<script src="01-jsonp.php?callback=fn"></script>
  • 然后需要在根目录下创建一个PHP的文件来调用js脚本
  • **示例代码 : **
<?php
$fn = $_GET['callback'];
// echo "alert(1)";    // 服务器返回的js代码是可以直接在浏览器中执行的
echo $fn."('xiba')";

$http服务

  • **示例代码 : **
<body ng-app="app" ng-controller="appController">

<script src="../js/angular.js"></script>
<script>
    var app = angular.module('app', []);
    // 注入$http模块
    app.controller('appController', ['$scope', '$http', function ($scope, $http) {
        // get请求
        $http({
            // 请求地址 自己在网上找个地址 模拟一下
            url: '02.php',
            // 请求方式
            method: 'get',
            // get方式传递参数  在传递过程当中 会自动帮你转成 get.php?name=xiba 传递时->name:xiba
            parmas:{
                name:'xiba'
            }
        }).success(function (res) {
            // 成功回调 angular版本是1.6以下 1.6以上不是用success回调
            console.log(res);
        }).error(function (error) {
            // 失败回调 angular版本是1.6以下 1.6以上不是用error回调
            console.log(error);
        });

        // post请求
        $http({
            url:'02.php',
            method:'post',
            // post 请求必须设置请求头
            // 当设置请求头的时候为application/x-www-form-urlencoded是以soap 以对象形式传递.
            // SOAP: 以对象形式来进行传递
            // RESTFUL:json串形式进行传递。
            headers:{
                'Content-Type':'application/x-www-form-urlencoded'
            },
            //data:{data:{} 传参形式  在传递数据时,是以json来传递的name:"xiba" json串 }
            data:'name:xiba'
        });
    }]);
</script>
</body>

自定义服务

什么是服务

  • angular在一开始就帮我们定义一些功能。我可以直接使用这些功能。
    都是一个方法或者一个对象的形式来调用指定的功能。
  • 想要使用这些服务。必须得要注入。
  • 谓服务是将一些通用性的功能逻辑进行封装方便使用,AngularJS允许将自定义服务。

内置服务:

  • $location $log $timeout $interval $http $filter
  • angular允许开发自己根据自己的需求来自定义自己的功能。

自定义服务分为三种

  • factory 直接就是一个对象
    service 通过new形式创建的对象 就可以在里面使用this.
    provider对上面定义的服务进行配置。 可以在开始的时候,让服务有哪些功能 , 或是去掉哪些。
  • 服务本质就是一个对象或函数,所以自定义服务就是要返回一个对象或函数以供使用。
  • 服务它是一个单例。
  • value 当作是一个全局常量
factory自定义服务 --> 直接就是一个对象
  • **示例代码 : **
<body ng-app="app" ng-controller="appController">

<h3>{{date}}</h3>
<h3>{{dateTime}}</h3>

<script src="../js/angular.js"></script>
<script>
    // 创建模块
    var app = angular.module('app', []);

    // 自定义服务 factory
    app.factory('myFac1', function () {
        return function () {
            console.log('自定义了一个服务');
        }
    });
    // 自定义服务 factory
    app.factory('myFac2', function () {
        function say() {
            console.log('hello');
        }

        function hellow() {
            console.log('hello wawa');
        }

        return {
            say1: say,
            say2: hellow
        }
    });
    // 自定义服务
    app.factory('showTime', ['$filter', function ($filter) {
        function showDate() {
            var dateTime = new Date();
            return $filter('date')(dateTime, 'yyyy-MM-dd');
        }

        function showDateTime() {
            var dateTime = new Date();
            return $filter('date')(dateTime, 'yyyy-MM-dd hh:mm:ss')
        }

        return {
            showDate: showDate,
            showDateTime: showDateTime
        }
    }]);

    // 创建控制器
    app.controller('appController', ['$scope', 'myFac1', 'myFac2', 'showTime', function ($scope, myFac1, myFac2, showTime) {
        /*
         myFac1();
         myFac2.say1();
         myFac2.say2();
         */

        $scope.date = showTime.showDate();
        $scope.dateTime = showTime.showDateTime();
    }]);
</script>

</body>
service自定义服务 --> 通过new出来一个对象 可以使用this
  • **示例代码 : **
<body ng-app="app" ng-controller="appController">
<script src="../js/angular.js"></script>
<script>
    var app = angular.module('app', []);

    app.service('mySer', function () {
        this.sayHellow = function () {
            console.log('hellow');
        }
        this.showTime = function () {
            console.log('show');
        }
    });
    app.service('formDate', function () {
        // 把一个对象转成name=xiba&age=10
        this.formD = function (obj) {
            var str = '';
            for (var key in obj) {
                str += key + '=' + obj[key] + '&'
            }
            return str.slice(0);
        }
    });

    app.controller('appController', ['$scope', 'mySer', 'formDate', '$http', function ($scope, mySer, formDate, $http) {
        /*
         mySer.sayHellow();
         mySer.showTime();
         var obj = {name:'xx',age:'11'}
         var str = formDate.formD(obj);
         console.log(str);
         */
        // 自定义一个php文件引入
        $http({
            url:'04-post.php',
            method:'post',
            headers:{
                'Content-Type':'application/x-www-form-urlencoded'
            },
            data:formDate.formD({
                name:"xiba",
                age:10
            })
        }).success(function (res) {
            alert(res);
        });
    }]);

</script>
</body>
value自定义服务 --> 全局常量
  • **示例代码 : **
<body ng-app="app" ng-controller="appController">
<script src="../js/angular.js"></script>
<script>
    var app = angular.module('app',[]);
    /*
     * 常量:其值始终保持不变的量。
     * 变量:其值可以发生变化的量。
     * */
    app.value('version','1.1');
    app.value('key','xiba');
    app.value('url','www.baidu.com');

    /*2.创建控制器
     * 可扩展性。需求改动时, 不需要动太多的代码。
     * */
    app.controller('appController',['$scope','version','key',function ($scope,version,key) {
        console.log(key);
    }]);
</script>
</body>

配置块

  • 配置服务, 可以在开始的时候,让服务有哪些功能 , 或是去掉哪些。

  • 通过config方法实现对模块的配置,AngularJS中的服务大部分都对应一个“provider”,用来执行与对应服务相同的功能或对其进行配置。

  • 比如$log$http$location都是内置服务

  • 相对应的provider分别是$logProvider$httpProvider$locationPorvider

  • **示例代码 : **

<body ng-app="app" ng-controller="appController">

<h3>{{name | chaUppercase}}</h3>

<script src="../js/angular.js"></script>
<script>
    var app = angular.module('app', []);
    app.controller('appController', ['$scope', '$log', function ($scope, $log) {
        $log.log('debug');
        $scope.name = 'xiba';
    }]);
    /*配置:
     * 配置服务, 可以在开始的时候,让服务有哪些功能 , 或是去掉哪些。
     * */
    app.config(['$logProvider', '$filterProvider', function ($logProvider, $filterProvider) {
        $logProvider.debugEnabled(false);
        $filterProvider.register('chaUppercase', function () {
            return function (input) {
                return input[0].toUpperCase() + input.slice(1);
            }
        });
    }]);
</script>
</body>

运行块

  • **示例代码 : **
<body ng-app="app" ng-controller="appController">
<h1>{{name}}</h1>
<h2>{{key}}</h2>

<script src="../js/angular.js"></script>
<script>
    var app = angular.module('app', []);
    app.controller('appController', ['$scope', function ($scope) {

    }]);
    /*
     * 在开发中, 运行块,就用户一进来就要去执行的一任务,都可以放到run里面
     * */

    angular.module('app').run(['$rootScope', '$http', function ($rootScope, $http) {
        $rootScope.name = 'run';
        $http({
            url: '07-get.php',
            method: 'get',
        }).success(function (res) {
            $rootScope.key = res;
        }).error(function (error) {

        });
    }]);
</script>
</body>

Angular路由小demo

  • 示例代码 : style
<style>
    * {
        margin: 0;
        padding: 0;
        list-style: none;
    }

    .title {
        width: 800px;
        height: 64px;
        line-height: 64px;
        background: #000;
        color: #fff;
        margin: 0 auto;
        margin-top: 50px;
        display: flex;
    }

    .title li {
        flex: 1;
        float: left;
        text-align: center;
    }

    .content {
        width: 798px;
        height: 500px;
        margin: 0 auto;
        border: 1px solid #000;
    }

    a {
        text-decoration: none;
        color: #fff;
        font-size: 25px;
    }

</style>
  • 示例代码 : HTML&&Js

<body ng-app="app" >

<ul class="title">
    <li><a href="#/index/1">首页</a></li>
    <li><a href="#/index/2">流行</a></li>
    <li><a href="#/index/3">复古</a></li>
</ul>
<div class="content">
    <div ng-view></div>
</div>

<script src="../js/angular.js"></script>
<script src="../js/angular-route.js"></script>
<script>
    /* 配置路由
     * 传参两步:
     * 1.配置时,定义参数$routeProvider.when('/index/:id)
     * 2.跳转时,传递对应的参数   <a href="#/index/1">首页</a>
     * 3.获取参数: 在绑定的控制器当中,注入服务$routeParams
     *   app.controller('indexController',['$scope','$routeParams',function ($scope,$routeParams) {
     * */
    var app = angular.module('app', ['ngRoute']);
    app.controller('appController', ['$scope', '$routeParams', '$http', function ($scope, $routeParams, $http) {
        $http({
            url: '11-listMusic.php',
            method: 'get',
            params: {
                id: $routeParams.id
            }
        }).success(function (res) {
            $scope.listM = res;
        })
    }]);
    app.config(['$routeProvider', function ($routeProvider) {
        $routeProvider.when('/index/:id', {
            templateUrl: '11-music_tpl.html',
            controller: 'appController'
        }).otherwise({
            // 设置默认跳转的路由
            redirectTo: 'index/1'
        });
    }]);
</script>
</body>
  • 示例代码 : 案例中的这个地址: url: '11-listMusic.php'
<?php

$list = array(
    array('id'=>1,'pid'=>2,'text'=>'我很丑可是我很温柔'),
    array('id'=>2,'pid'=>2,'text'=>'蒲公英的约定'),
    array('id'=>3,'pid'=>2,'text'=>'你我的约定'),
    array('id'=>4,'pid'=>3,'text'=>'pretty boy'),
    array('id'=>5,'pid'=>3,'text'=>'See You Again'),
    array('id'=>6,'pid'=>2,'text'=>'甜甜的'),
    array('id'=>7,'pid'=>1,'text'=>'再见我的爱人'),
    array('id'=>8,'pid'=>2,'text'=>'心中的日月'),
    array('id'=>9,'pid'=>3,'text'=>'Let It Go'),
    array('id'=>10,'pid'=>1,'text'=>'不要说再见'),
    array('id'=>11,'pid'=>3,'text'=>'Rise'),
    array('id'=>12,'pid'=>2,'text'=>'再见'),
    array('id'=>13,'pid'=>1,'text'=>'追梦人'),
    array('id'=>14,'pid'=>2,'text'=>'不能说的秘密'),
    array('id'=>15,'pid'=>4,'text'=>'오늘 하루'),
    array('id'=>16,'pid'=>1,'text'=>'昨日重现'),
    array('id'=>17,'pid'=>3,'text'=>'Love Me like you Do'),
    array('id'=>18,'pid'=>2,'text'=>'好久不见'),
    array('id'=>19,'pid'=>1,'text'=>'独角戏'),
    array('id'=>20,'pid'=>2,'text'=>'K歌之王'),
    array('id'=>21,'pid'=>1,'text'=>'往事随风'),
    array('id'=>22,'pid'=>3,'text'=>'Just Like Fire'),
    array('id'=>23,'pid'=>4,'text'=>'さよならの夏'),
    array('id'=>24,'pid'=>4,'text'=>'江南Style'),
    array('id'=>25,'pid'=>4,'text'=>'仆が死のうと思'),
    array('id'=>26,'pid'=>1,'text'=>'海阔天空'),
    array('id'=>27,'pid'=>4,'text'=>'天空之城'),
    array('id'=>28,'pid'=>1,'text'=>'不再犹豫'),
    array('id'=>29,'pid'=>4,'text'=>'仆が死のうと思'),
    array('id'=>30,'pid'=>3,'text'=>'Heart And soul'),
    array('id'=>31,'pid'=>4,'text'=>'오늘 하루'),
    array('id'=>32,'pid'=>1,'text'=>'往事只能回味'),
    array('id'=>33,'pid'=>3,'text'=>'Bang Bang'),
    array('id'=>34,'pid'=>4,'text'=>'さよならの夏'),
    array('id'=>35,'pid'=>3,'text'=>'Same Old Love'),
    array('id'=>36,'pid'=>4,'text'=>'さよならの夏'),
    array('id'=>37,'pid'=>4,'text'=>'恋恋风尘'),
);
$id = $_GET['id'];
$tempArray = array();
foreach ($list as $key=>$value){
    if ($id == $value['pid']){
       $tempArray[] = $value;
    }
}
echo  json_encode($tempArray);
  • 模版 案例中的这个地址 : templateUrl: '11-music_tpl.html'
<ul>
    <li ng-repeat="music in listM">{{music.text}}</li>
</ul>

好咯! 齐活咯! 大家晚安,有什么问题欢迎留言咨询 !!!

相关文章

网友评论

    本文标题:Angular自定义服务&&路由

    本文链接:https://www.haomeiwen.com/subject/aoekattx.html