오류가 발생하지 않고 모듈의 존재를 확인하는 방법은 무엇입니까?
각도 1.2에서는ngRoute
별도의 모듈이기 때문에 다음과 같은 다른 커뮤니티 라우터는 다음과 같습니다.ui.router
대신.
복수의 다른 라우터 실장용으로 동작하는 것을 목적으로 한 오픈소스 모듈을 쓰고 있습니다.그러면 어떤 라우터가 로딩되어 있는지 어떤 라우터가 있는지 어떻게 확인할 수 있을까요?
모듈 내 공장 내에서 다음 작업을 수행 중이지만 예상대로 작동하지 않습니다.
if (angular.module("ngRoute"))
// Do ngRoute-specific stuff.
else if (angular.module("ui.router"))
// Do ui.router-specific stuff.
로딩되지 않은 모듈에 대해 오류가 발생합니다.예를 들어, 앱이 다음을 사용하고 있는 경우ui.router
다음 에러가 발생합니다.ngRoute
체크:
발견되지 않은 오류: [$injector:nomod] 모듈을 사용할 수 없습니다.모듈 이름의 철자가 틀렸거나 로드하는 것을 잊었습니다.모듈을 등록할 경우 종속성을 두 번째 인수로 지정해야 합니다.
에러가 발생하지 않고 체크하는 방법은 알 수 없습니다만, 문제가 되는 것은,Uncaught Error
에러가 발생한 것은 아닙니다.이러한 에러를 검출하는 패턴은 다음과 같습니다.
try { angular.module("ngRoute") } catch(err) { /* failed to require */ }
오류가 검출되면 다른 모듈을 시험하고, 검출되지 않으면 첫 번째 모듈을 사용할 수 있습니다.
각 모듈에서 동일한 동작을 할 경우 다음과 같은 작업을 수행할 수 있습니다.이 경우 나열된 모듈 이름 중 첫 번째를 시도하는 함수를 정의하고 오류가 발생하면 다음 옵션을 사용해 보십시오.
var tryModules = function(names) {
// accepts a list of module names and
// attempts to load them, in order.
// if no options remain, throw an error.
if( names.length == 0 ) {
throw new Error("None of the modules could be loaded.");
}
// attempt to load the module into m
var m;
try {
m = angular.module(names[0])
} catch(err) {
m = null;
}
// if it could not be loaded, try the rest of
// the options. if it was, return it.
if( m == null ) return tryModules(names.slice(1));
else return m;
};
tryModules(["ngRoute", "ui.router"]);
모듈 자체보다는 서비스를 테스트합니다.
// In controller
if($injector.has('$route')){
}
if($injector.has('$state')){
}
// In angular config
if($injector.has('$routeProvider')){
}
if($injector.has('$stateProvider')){
}
원래 답은 적법하다.다만, 그 대신에, 모듈을 「찾거나 작성」할 필요가 있는 것입니다.여러 가지 사용 사례가 있지만 일반적으로 파일 로드 순서에 대해 걱정할 필요가 없습니다.이걸 넣어도 되고initialModules.js
...또는 모든 개별 서비스/하드웨어 파일의 맨 위는 다음과 같이 시작합니다.이 작은 기능은 저에게 매력적으로 작용합니다.
var initialModules = [
{name: 'app.directives', deps: ['ui.mask']},
{name: 'app.services'},
{name: 'app.templates'},
{name: 'app.controllers'}
];
initialModules.forEach(function(moduleDefinition) {
findOrCreateModule(moduleDefinition.name, moduleDefinition.deps);
});
function findOrCreateModule(moduleName, deps) {
deps = deps || [];
try {
angular.module(moduleName);
} catch (error) {
angular.module(moduleName, deps);
}
}
///// OR... in like "myDirective.js"
findOrCreateModule('app.directives').directive('myDirective', myDirectiveFunction);
꾸민다면angular.module
이름을 배열에 저장하려면 배열에 모듈 이름이 포함되어 있는지 확인할 수 있습니다.
angular.module을 장식합니다.
각도 로드 후 각도 모듈 로드를 시작하기 전에 이 작업을 수행해야 합니다.
모듈을 확인합니다.
if(angular.modules.indexOf("ngRoute") > -1) ...
그러나 모듈을 자동으로 로드하거나 생성하는 문제는 gulp-angular-filesort와 같은 것으로 더 잘 해결할 수 있습니다.그것은 정말 완벽하게 작동한다.
gulp-angular-filesort github 페이지에서:각도 자동 정렬모듈 정의 및 용도에 따른 JS 앱 파일
꿀꺽-주입과 함께 Angular 주입에 사용올바른 순서로 JS 애플리케이션 파일(스크립트)을 실행하여 모든 Uncaughed 오류를 제거합니다. [$injector:modulerr]
면책사항:저는 gul-angular-filesort와 제휴하지 않고, 수익만 많이 내고 사용합니다.
모듈 작성 시 체크만 하면 훨씬 더 좋은 해결책이 됩니다.콜백을 추가하려면 유틸리티 기능만 필요합니다.
//create a utility function to add a callback to object methods
//here we are making it a method of the underscore or lowdash object
//but it could be added to the angular global object or anything else
_.addCallBack = function (obj, originalMethodName, callBackMethod, context){
var fnOriginal = obj[originalMethodName],
outcome;
context = context || obj;
obj[originalMethodName] = function () {
var outcome = fnOriginal.apply(this, arguments);
callBackMethod.apply(this, arguments);
return outcome;
};
};
_.addCallBack(angular, "module", function(sModuleName, asDependencies){
if(_.contains(asDependencies, "ngRoute")){
//your logic here
//just loop through if you don't use underscore or lowdash
}
});
AngularJS 1.6.3 이상에는 $injector 서비스를 통해 모듈이 로드되었는지 확인할 수 있는 방법이 있습니다.
또한 1.6.7에는 일부에서 관심을 가질 수 있는 새로운 모듈을 로드할 수 있는 기능이 추가되었습니다.
언급URL : https://stackoverflow.com/questions/19206553/how-to-check-for-the-existence-of-a-module-without-an-error-being-raised
'programing' 카테고리의 다른 글
Pymongo를 사용하여 컬렉션의 모든 문서 가져오기 (0) | 2023.02.28 |
---|---|
SQL SELECT 문에서 패키지 상수를 사용하는 방법 (0) | 2023.02.28 |
Wordpress 폼에서 SOAP 웹 서비스를 호출하려면 어떻게 해야 합니까? (0) | 2023.02.28 |
토큰 기반 인증을 위한 JWT vs 쿠키 (0) | 2023.02.28 |
ORA-12519가 간헐적으로 발생하는 원인(TNS: 적절한 핸들러를 찾을 수 없음) (0) | 2023.02.28 |