Angular中调用未定义函数报错:ReferenceError: newFunction is not defined
在AngularJS中正确定义函数解决
ReferenceError问题 别着急,这个报错本质就是你在调用newFunction的时候,该函数还没被定义或者当前作用域访问不到。先梳理下你的问题场景:
你的问题代码
你在应用的config块里尝试调用newFunction(RestangularProvider),但函数未定义导致报错,现有代码如下:
var app = angular.module('rtsApp', ['ngMaterial', 'ngMessages', 'ngStorage','ngRoute', 'restangular','timepickerPop', 'ngStomp', 'ngCookies', 'angular-cron-gen','uiSwitch','ngMaterial', 'md.data.table']); app.config(function(RestangularProvider) { newFunction(RestangularProvider);//I need newFunction here RestangularProvider.setDefaultHeaders({ "X-API-KEY": "sks@2017", "Content-Type": "application/json" }); });
收到的错误提示:
Failed to instantiate module rtsApp due to:
ReferenceError: newFunction is not definedat http://localhost:3000/dist/js/scripts.min.js:1738:5 at Object.invoke (http://localhost:3000/dist/js/vendor.min.js:82:460) at d (http://localhost:3000/dist/js/vendor.min.js:80:333) at http://localhost:3000/dist/js/vendor.min.js:80:472 at q (http://localhost:3000/dist/js/vendor.min.js:46:7) at g (http://localhost:3000/dist/js/vendor.min.js:80:234) at gb (http://localhost:3000/dist/js/vendor.min.js:84:352) at c (http://localhost:3000/dist/js/vendor.min.js:60:57) at Wc (http://localhost:3000/dist/js/vendor.min.js:60:370) at ye (http://localhost:3000/dist/js/vendor.min.js:59:45)
解决方案
方案1:简单提前定义普通函数
如果你的newFunction逻辑比较简单,直接在模块定义和config块之前定义这个函数就行——JavaScript是函数作用域,只要调用前定义就能访问到:
// 先定义newFunction,放在模块代码之前 function newFunction(restangularProvider) { // 在这里写你的函数逻辑,比如配置Restangular的其他规则 // 示例:restangularProvider.setBaseUrl('/api/v1'); } var app = angular.module('rtsApp', ['ngMaterial', 'ngMessages', 'ngStorage','ngRoute', 'restangular','timepickerPop', 'ngStomp', 'ngCookies', 'angular-cron-gen','uiSwitch','ngMaterial', 'md.data.table']); app.config(function(RestangularProvider) { newFunction(RestangularProvider);//现在可以正常调用了 RestangularProvider.setDefaultHeaders({ "X-API-KEY": "sks@2017", "Content-Type": "application/json" }); });
方案2:使用Angular Provider(推荐,符合规范)
如果newFunction的逻辑复杂,或者需要在多个地方复用,推荐把它封装成Angular Provider,遵循依赖注入的规范,让代码更模块化、可维护:
var app = angular.module('rtsApp', ['ngMaterial', 'ngMessages', 'ngStorage','ngRoute', 'restangular','timepickerPop', 'ngStomp', 'ngCookies', 'angular-cron-gen','uiSwitch','ngMaterial', 'md.data.table']); // 定义一个用于配置Restangular的Provider app.provider('RestangularConfig', function() { // 把你的newFunction逻辑放在这里 this.configure = function(restangularProvider) { // 这里写你的配置逻辑 // 示例:restangularProvider.setRequestInterceptor(function(element) { return element; }); }; // Provider必须包含$get方法,即使不需要返回内容 this.$get = function() { return {}; }; }); // 在config块中注入这个Provider并调用方法 app.config(function(RestangularProvider, RestangularConfigProvider) { RestangularConfigProvider.configure(RestangularProvider); RestangularProvider.setDefaultHeaders({ "X-API-KEY": "sks@2017", "Content-Type": "application/json" }); });
这种方式更符合Angular的设计思想,方便后续扩展和测试。
内容的提问来源于stack exchange,提问作者Suvin Kumar
相关产品推荐
相关产品推荐

