programing

Angular의 선택적 종속성JS

showcode 2023. 3. 6. 21:39
반응형

Angular의 선택적 종속성JS

Angular에서 컨트롤러를 구현하려고 합니다.여러 페이지에 걸쳐 사용되는 JS.그것은 몇 가지 서비스를 이용한다.그 중 일부는 모든 페이지에 로드되어 있지만 일부는 로드되어 있지 않습니다.다른 파일에 정의되어 있고, 이 파일들은 독립적으로 로드됩니다.그러나 모든 페이지에 이러한 서비스를 로드하지 않으면 다음과 같은 오류가 발생합니다.

Error: Unknown provider: firstOtionalServiceProvider <- firstOtionalService

그래서 모든 페이지에 스크립트를 로드해야 합니다.Angular에서 종속성을 옵션으로 선언할 수 있습니까?예:

myApp.controller('MyController', ['$scope', 'firstRequiredService', 'secondRequiredService', 'optional:firstOptionalService', 'optional:secondOptionalService', function($scope, firstRequiredService, secondRequiredService, firstOptionalService, secondOptionalSerivce){

    // No need to check, as firstRequiredService must not be null
    firstRequiredService.alwaysDefined();

    // If the dependency is not resolved i want Angular to set null as argument and check
    if (firstOptionalService) {
        firstOptionalService.mayBeUndefinedSoCheckNull();
    }

}]);

자동주사를 사용하지 않는 것 같아요그러나 인젝터를 주입하고 서비스를 확인할 수 있습니다.

myApp.controller('MyController', [
    '$scope', '$injector', 'firstRequiredService', 'secondRequiredService', 
    function ($scope, $injector, firstRequiredService, secondRequiredService) {
        if ($injector.has('firstOptionalService')) {
            var firstOptionalService = $injector.get('firstOptionalService');
        }
    }
]);

아니요, Angular는 아직 기본 제공 시 옵션 종속성을 지원하지 않습니다.모든 종속성을 모듈에 넣고 하나의 Javascript 파일로 로드하는 것이 좋습니다.다른 종속성 세트가 필요한 경우 - 다른 JS에 다른 모듈을 만들고 모든 공통 종속성을 공통 JS에 두는 것을 고려하십시오.

그러나 당신이 설명한 행동은 서비스를 통해 달성될 수 있습니다.주사만 하면 됩니다.$injector컨트롤러에 대한 의존관계를 모두 해제하고 컨트롤러에서 의존관계를 수동으로 풀하여 컨트롤러가 존재하는지 확인합니다.이상입니다.

index.syslog:

<!DOCTYPE html>
<html data-ng-app="myApp">
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js"></script>
    <script src="app.js"></script>
    <script src="1.js"></script>
    <script src="2.js"></script>
    <title>1</title>
  </head>
  <body data-ng-controller="DemoController">
  </body>
</html>

app.filename:

var myApp = angular.module('myApp', []);

myApp.service('commonService', function(){
    this.action = function(){
        console.log('Common service is loaded');
    }
});

myApp.controller('DemoController', ['$scope', '$injector', function($scope, $injector){
    var common;
    var first;
    var second;

    try{
        common = $injector.get('commonService');
        console.log('Injector has common service!');
    }catch(e){
        console.log('Injector does not have common service!');
    }
    try{
        first = $injector.get('firstService');
        console.log('Injector has first service!');
    }catch(e){
        console.log('Injector does not have first service!');
    }
    try{
        second = $injector.get('secondService');
        console.log('Injector has second service!');
    }catch(e){
        console.log('Injector does not have second service!');
    }

    if(common){
        common.action();
    }
    if(first){
        first.action();
    }
    if(second){
        second.action();
    }
}]);

1.120:

myApp.service('firstService', function(){
    this.action = function(){
        console.log('First service is loaded');
    }
});

2.120:

myApp.service('secondService', function(){
    this.action = function(){
        console.log('Second service is loaded');
    }
});

플랭크에서 생중계하세요!가지고 놀려고 해 보다<script>태그를 지정하고 콘솔 출력을 감시합니다.

추신. 그리고 @Problematic이 말했듯이$injector.has()AngularJS 1.1.5부터 시작합니다.

$injector를 사용하자는 @Proplatic의 제안에 찬성할 것 같습니다.다만, 생각할 수 있는 다른 솔루션이 있습니다.즉, 모든 서비스를 기본값으로 등록합니다).null예를 들어)를 부트스트랩 파일에 저장합니다.추가 파일이 로드되면 이후 정의가 기본 정의를 재정의하여 원하는 효과를 어느 정도 생성합니다.

var app = angular.module('plunker', []);

app.value("service1", null)
   .value("service2", null)
   .factory("service1", function() { return "hello"; });

app.controller('MainCtrl', function($scope, service1, service2) {
  console.log(service1); // hello
  console.log(service2); // null
});

데모 링크

이렇게 해결했습니다.

var deps = [];

try {
    //Check if optionalModule is available
    angular.module('app').requires.push('optionalModule');
    deps.push('optionalModule');
} catch(e){
    console.log("Warn: module optionalModule not found. Maybe it's normal");
}

angular.module('app', deps).factory('stuff', function($injector) {
    var optionalService;

    if($injector.has('optionalService')) {
        optionalService = $injector.get('optionalService');
    } else {
        console.log('No waffles for you, dear sir');
    }
});

이렇게 해보세요.

try {
    angular.module('YourModule').requires.push('Optional dependency module');
} catch(e) {
    console.log(e)
}

requires는 의존관계 모듈의 배열입니다.

언급URL : https://stackoverflow.com/questions/18542032/optional-dependencies-in-angularjs

반응형