【问题标题】:AngularJS/JS-how to convert hard coded value in factory by server returned valueAngularJS/JS-如何通过服务器返回值转换工厂中的硬编码值
【发布时间】:2018-01-16 20:00:48
【问题描述】:

我正在尝试实现在“http://plnkr.co/edit/zsh2Bt7jBl1Z2mKKqlwa?p=preview”上给出的解决方案,它按预期工作(使用硬编码的用户详细信息),但现在当我尝试通过服务器响应替换硬编码值时,我无法对此 - 请帮助

 var wmapp = angular
    .module('distance', [ 'wmapp.factory_restaurants', 'greatCircles' ])

    // RESTAURANTLIST CONTROLLER
    .controller(
            'restaurantlistController',
            function($scope, $rootScope, restaurantsFactory, position,
                    GreatCircle) {
                "use strict";
                $scope.restaurantList = restaurantsFactory.getRestaurants(); 
    // call
                // to
                // restaurantfactory
                $scope.position = position;

                $scope.distanceTo = function(restaurant) {
                    var distance = GreatCircle.distance(restaurant.long,
                            restaurant.lat, position.longitude,
                            position.latitude)
                    restaurant.distance = distance;
                    distance = distance.toFixed(1);
                    return distance;
                };
                $scope.totalDisplayed = 2; // implementing a load more
                // capability
                $scope.loadMore = function() {
                    $scope.totalDisplayed += 20;
                };
            })

    .factory(
            'position',
            function($rootScope) {

                console.log('building position')

                var position = {};

                // 1ST / AUTO GEOLOCATION OF USER
                // displays a popup to indicate current user location -
                // (disabled)
                // onSuccess Callback - This method accepts a Position
                // object, which contains the current GPS coordinates
                var onSuccess = function(position2) {

                    console.log(position2.coords.latitude)
                    console.log(position2.coords.longitude)

                    //alert("latitude and longitude------"
                        //  + position2.coords.latitude + "----------"
                            //+ position2.coords.longitude);

                      position.latitude = "26.805273";
                        position.longitude = "83.355463";

                    //position.latitude = position2.coords.latitude;
                    //position.longitude = position2.coords.longitude;

                    $rootScope.$digest()
                };

                function onError(error) { // onError Callback receives a
                    // PositionError object
                    alert('code: ' + error.code + '\n' + 'message: '
                            + error.message + '\n');
                }

                navigator.geolocation
                        .getCurrentPosition(onSuccess, onError);

                return position;

            })

  angular
    .module('wmapp.factory_restaurants', [ 'greatCircles' ])

    .factory(
            'restaurantsFactory',
            function() {
                "use strict";
                var factory = {
                    Restaurants : [
                            {
                                Name : '11111111111',
                                venueType : 'Electrician ',
                                subCuisine : 'Fan',
                                subsubCuisine : 'Greesing, Bnding',
                                address : 'abc',
                                city : 'test',
                                country : 'xxx',
                                countryCode : 'kk',
                                lat : 36.805273,
                                long : 73.355463,
                            },
                            {
                                Name : '222222222',
                                venueType : 'Electrician ',
                                subCuisine : 'Fan',
                                subsubCuisine : 'Greesing, Bnding',
                                address : 'hii',
                                city : 'xyz',
                                country : 'abc',
                                countryCode : 'oo',
                                lat : 85.320918,
                                long : 43.006271,
                            } ],
                    getRestaurants : function() {
                        return factory.Restaurants;
                    },
                };
                return factory;

            });

  // 2ND / CALCULATE DISTANCE BETWEEN TWO GEOCOORDIANTES
  var GreatCircle = {

   validateRadius : function(unit) {
    var r = {
        'KM' : 6371.009,
        'MI' : 3958.761,
        'NM' : 3440.070,
        'YD' : 6967420,
        'FT' : 20902260
    };
    if (unit in r)
        return r[unit];
    else
        return unit;
    },

    distance : function(lat1, lon1, lat2, lon2, unit) {
    console.log(arguments)
    if (unit === undefined)
        unit = 'KM';
    var r = this.validateRadius(unit);
    lat1 *= Math.PI / 180;
    lon1 *= Math.PI / 180;
    lat2 *= Math.PI / 180;
    lon2 *= Math.PI / 180;
    var lonDelta = lon2 - lon1;
    var a = Math.pow(Math.cos(lat2) * Math.sin(lonDelta), 2)
            + Math.pow(Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1)
                    * Math.cos(lat2) * Math.cos(lonDelta), 2);
    var b = Math.sin(lat1) * Math.sin(lat2) + Math.cos(lat1)
            * Math.cos(lat2) * Math.cos(lonDelta);
    var angle = Math.atan2(Math.sqrt(a), b);

    return angle * r;
    },

bearing : function(lat1, lon1, lat2, lon2) {
    lat1 *= Math.PI / 180;
    lon1 *= Math.PI / 180;
    lat2 *= Math.PI / 180;
    lon2 *= Math.PI / 180;

    console.log(lat1);
    console.log(lon1);
    console.log(lat2);
    console.log(lon2);

    var lonDelta = lon2 - lon1;
    var y = Math.sin(lonDelta) * Math.cos(lat2);
    var x = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1)
            * Math.cos(lat2) * Math.cos(lonDelta);
    var brng = Math.atan2(y, x);
    brng = brng * (180 / Math.PI);

    if (brng < 0) {
        brng += 360;
    }

    return brng;
    },

    destination : function(lat1, lon1, brng, dt, unit) {
    if (unit === undefined)
        unit = 'KM';
    var r = this.validateRadius(unit);
    lat1 *= Math.PI / 180;
    lon1 *= Math.PI / 180;
    var lat3 = Math.asin(Math.sin(lat1) * Math.cos(dt / r) + Math.cos(lat1)
            * Math.sin(dt / r) * Math.cos(brng * Math.PI / 180));
    var lon3 = lon1
            + Math.atan2(Math.sin(brng * Math.PI / 180) * Math.sin(dt / r)
                    * Math.cos(lat1), Math.cos(dt / r) - Math.sin(lat1)
                    * Math.sin(lat3));

    return {
        'LAT' : lat3 * 180 / Math.PI,
        'LON' : lon3 * 180 / Math.PI
    };
   }

 };

 angular.module('greatCircles', []).value('GreatCircle', GreatCircle)

   /*
    * window.onload = function(){ document.getElementById("dist").innerHTML 
    =
    * Math.round(( GreatCircle.distance(48.853139,2.368999, 48.826136, 
    2.321793) *
     * 10 ) // fake data. Shall be replaced with user location + restaurant 
     location
     * 10 ); }
     */

这是我在调用“浏览器上的http://localhost:3030/sez/api/user/”时的服务器响应

  [
                            {
                                Name : '11111111111',
                                venueType : 'Electrician ',
                                subCuisine : 'Fan',
                                subsubCuisine : 'Greesing, Bnding',
                                address : 'abc',
                                city : 'test',
                                country : 'xxx',
                                countryCode : 'kk',
                                lat : 36.805273,
                                long : 73.355463,
                            },
                            {
                                Name : '222222222',
                                venueType : 'Electrician ',
                                subCuisine : 'Fan',
                                subsubCuisine : 'Greesing, Bnding',
                                address : 'hii',
                                city : 'xyz',
                                country : 'abc',
                                countryCode : 'oo',
                                lat : 85.320918,
                                long : 43.006271,
                            } ]

这就是视图-

  <div  ng-repeat="restaurant in restaurantList | orderBy: 'distance' | 
  limitTo:totalDisplayed" href="#">
        <article class="item_frame">
      <div class="marker_left_container">
        <span class="venu_type_text">{{restaurant.venueType}}</span>
        <span class="distance_from_user_rest"> distance: 
  {{distanceTo(restaurant)}}</span>
        <span class="distance_from_user_rest2">from current location</span>
      </div>
      <div class="restaurant_details_container">
        <h1 class="restaurant_name_inlist">{{restaurant.Name}}</h1>
        <span class="restaurant_detail_inlist2">{{restaurant.subCuisine}}  
   <br />

    {{restaurant.subsubCuisine}}</span>
        <span class="restaurant_address">{{restaurant.address}}, <br />
        </span>
        <span class="restaurant_address">{{restaurant.cp}}, 
   {{restaurant.city}}  <br />

        </span>
        <span class="restaurant_others">{{restaurant.phoneNumber}} <br />
        </span>
        <span class="restaurant_others">{{restaurant.website}}  <br />
        </span>
             </div>

      </article><!--main article frame 1 -->

    </div>
    <button class="button button-outline button-stable custom_button_lau" ng-click="loadMore()">Load more</button>
  </div>
    </div>

【问题讨论】:

    标签: jquery angularjs angularjs-scope


    【解决方案1】:

    您应该使用此方法从您工厂的服务器获取数据

        angular
            .module('wmapp.factory_restaurants', [ 'greatCircles' ])    
            .factory(
                 'restaurantsFactory',
                  function($http) {
                      return {
                         getRestaurants: function (url) {
                         return $http.get(url);
                       }
               };
            });
    

    在控制器文件中:

    $scope.restaurantList = {};
    restaurantsFactory.getRestaurants(url)
                    .success(function (response) {
                        $scope.restaurantList = response;
                        console.log($scope.restaurantList);
                    }, function (error) {
                        console.log("Error in getting data: " + error);
                    });
    

    现在在控制器中,您可以替换或对接收到的对象执行任何其他计算。

    【讨论】:

    • 您能否告诉我您在获取数据时是否收到任何错误(http 响应),或者可以在此处发送收到的响应
    • 错误:[orderBy:notarray] errors.angularjs.org/1.5.8/orderBy/… at angular.min.js:6 at angular.min.js:172 at fn (eval at compile (angular.min.js:233), :4:256) at angular.min.js:128 at m.$digest (angular.min.js:143) at m.$apply (angular.min.js:146) at l (angular.min .js:97) 在 J (angular.min.js:102) 预期的数组但收到:{"$$state":{"status":1,"value":{"data":
    • orderBy 过滤器不正确,因为它搜索餐厅对象中归档的“距离”,因此请尝试删除此过滤器,如果您想要归档距离,则在控制器中的餐厅列表上循环并计算距离并附加它在 restaurantList 中,然后传递给 UI
    • 我更新了我的答案。请在控制台查看服务器数据,一定会对您有所帮助。
    • 完美,至少我现在可以看到一些结果 :) Thx - 这个 #1 有两个问题 - 距离显示“距离:距当前位置的 NaN” #2 - 在控制台中,我可以看到此错误一次“错误:orderBy:notarray Value is not array-like Expected array but received: {}”但在此之后,所有字段都被加载
    猜你喜欢
    • 2015-11-25
    • 2016-01-25
    • 1970-01-01
    • 2015-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-15
    • 1970-01-01
    相关资源
    最近更新 更多