How can I communicate a settings object from a controller to services?

后端 未结 4 555
终归单人心
终归单人心 2021-02-06 11:56

tl;dr;

I need to communicate state which several services need and originates in data bound to the scope of a controller. What would a good and \'Angular zen\' way to

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-06 12:38

    You have two options:

    1. Use shared service in combination with $watch. I.e. what you implemented, or put differently the Mediator Pattern.
    2. Use $scope.$broadcast and/or $scope.$emit with $scope.$on events to communicate changes.

    Personally I don't see anything wrong with option (1). I also don't consider that to be global state in the traditional sense. Your configuration is contained within the Configuration service, you can only access this service through DI injection which makes it testable.

    One possible improvement is to create a ConfigMediator service and move the update and callback functionality to it to separate concerns.

提交回复
热议问题