it-source

angularjs 1.5 성분 의존성 주입

criticalcode 2023. 4. 6. 21:46
반응형

angularjs 1.5 성분 의존성 주입

이것은 새로운 것처럼 들릴지 모르지만, 나는 angularjs 컴포넌트에 대해 튜토리얼을 따라왔다.

컴포넌트는 처음이고 상수는 어떻게 주입합니까?Utils또는authService내 컴포넌트에 이런 식으로요?

app.component('tlOverallHeader', {
    bindings: {
        data: '='
    },
    templateUrl: 'js/indexTimeline/components/tl_overallHeader/templates/tl_overallHeader.html',
    controller: function() {
        this.ms = 'tlOverallheader!'
    }
})

고마워!

다음과 같이 컴포넌트 컨트롤러에 서비스를 주입할 수 있습니다.

angular.module('app.module')
        .component('test', {
            templateUrl: 'views/someview.html',
            bindings: {
                subject: '='
            },
            controller: ['$scope', 'AppConfig', TestController]
        });

    function TestController(scope, config) {
        scope.something = 'abc';
    }

또는 다음과 같습니다.

angular.module('app.module')
        .component('test', {
            templateUrl: 'views/someview.html',
            bindings: {
                subject: '='
            },
            controller: TestController
        });

    TestController.$inject = ['$scope', 'AppConfig']
    function TestController(scope, config) {
        scope.something = 'abc';
    }

스탠드아론 컨트롤러와 마찬가지로 컴포넌트의 컨트롤러에 서비스를 삽입할 수 있어야 합니다.

controller: function(Utils, authService) {
    this.ms = 'tlOverallheader!'

    authService.doAuthRelatedActivities().then(...);
}

인정된 답변은 최소화가 안전하지 않습니다.여기서도 최소 안전 의존성 주입 표기를 사용할 수 있습니다.

controller: ['Utils', 'authService',
  function(Utils, authService) {
    this.ms = 'tlOverallheader!'

    authService.doAuthRelatedActivities().then(...);
  },
]

Factory 스타일 서비스를 사용하는 기능 스타일 프로그래밍의 경우 다음 구문이 작업을 수행합니다.

angular.module('myApp')

.component('myComponent', {
    templateUrl: 'myTemplate.html',
    controller: ['myFactory', function(myFactory){
        var thisComponent = this;
        thisComponent.myTemplatemsg = myFactory.myFunc();
    }]
})


.factory('myFactory', [ function(){

    return {
        myFunc: function(){
                    return "This message is from the factory";
                }
    };
}]);     

주의사항:컴포넌트에 대해 설정한 컴포넌트 서비스/팩토리는 부모 스코프 및 기타 컴포넌트 스코프를 포함한 앱의 다른 장소에서도 주입할 수 있습니다.이것은 강력하지만 쉽게 남용될 수 있습니다.따라서 컴포넌트는 자신의 범위 내에서만 데이터를 수정하여 누가 무엇을 수정하는지 혼동하지 않도록 하는 것이 좋습니다.상세한 것에 대하여는, https://docs.angularjs.org/guide/component#component-based-application-architecture 를 참조해 주세요.
단, 상기 링크의 논의조차도 쌍방향 구속력 있는 속성가치의 주의적 사용에 대해서만 다루고 있습니다.'='바인딩 오브젝트를 사용하는 경우.따라서 부품 서비스 및 공장에도 동일한 논리가 적용되어야 한다.다른 컴포넌트 범위 및/또는 부모 범위에서 동일한 서비스 또는 팩토리를 사용할 계획이라면 부모 범위 또는 의도하는 서비스/팩토리의 집합이 있는 곳에 서비스/팩토리를 설정하는 것을 권장합니다.특히 동일한 서비스/공장에서 다수의 컴포넌트를 사용하고 있는 경우에는 더욱 그렇습니다.찾기 어려운 임의의 컴포넌트 모듈에 배치하는 것은 바람직하지 않습니다.

언급URL : https://stackoverflow.com/questions/34891397/angularjs-1-5-component-dependency-injection

반응형