zoukankan      html  css  js  c++  java
  • angularJS中$http.get( ).success( )报错原因及解决方案

    一、问题描述:

    电脑安装的angular1.6.7版本,项目中使用了$http.get( ).success( ),控制台报错:

    $http.get(...).success is not a function
    

    就是说找不到success方法,同样也找不到error方法。

    二、原因分析

    经查询,从1.6版本开始,angular正式移除了success和error方法。从1.5版本开始,angular多出来then( )方法。因此,从1.6版本后不能使用success和error方法,可以采用then( )方法替代。

    三、使用$http.get( ).then( )替代
    原success代码示例:

    angular.module("app").controller("mainCtrl",["$http","$scope",function ($http,$scope) {
    	$http.get('data/positionList.json').success(function (resp) {
    		$scope.list=resp;
    		console.log($scope.list);
    	});
    }])
    

    直接将success换成then:

    angular.module("app").controller("mainCtrl",["$http","$scope",function ($http,$scope) {
    	$http.get('data/positionList.json').then(function (resp) {
    		$scope.list=resp;
    		console.log($scope.list);
    	});
    }])
    

    发现得到的数据有差异:
    这里写图片描述
    在使用success时得到的就是标红框部分数组,而使用then时得到的却是一个对象,数组成了对象的一个属性。
    因此在形参后面加上data属性即可解决:

    angular.module("app").controller("mainCtrl",["$http","$scope",function ($http,$scope) {
    	$http.get('data/positionList.json').then(function (resp) {
    		$scope.list=resp.data;
    		console.log($scope.list);
    	});
    }])
    

    四、备注:
    $http.post( ).success( )可正常使用,不会报错;
    使用 $http.post( ).then( )反而会报错。

  • 相关阅读:
    .vimrc
    GNU_makefile_template
    EM算法
    《设计模式之禅》学习笔记
    k-近邻算法
    机器学习基础
    《机器学习实战》学习笔记
    使用Apriori算法和FP-growth算法进行关联分析
    An ffmpeg and SDL Tutorial
    在Qt Creator中添加OpenCV库
  • 原文地址:https://www.cnblogs.com/twodog/p/12134752.html
Copyright © 2011-2022 走看看