This question revolves around design patterns. Rather than seeking a solution for achieving polymorphism in a service, I am interested in exploring the most widely accepted approach.
Imagine there is a service named getData which retrieves data from various sources such as a database, text file, or hardcoded input. The output is determined by the settings on the $scope within the controller. In this scenario, let's assume that the behavior of getData is influenced by the dataSource variable.
angular.module('testApp').controller('testController'), [$scope, myAwesomeService, function ($scope, myAwesomeService){
$scope.dataSource = 'database'; //defines the source of the data
$scope.getData = function() {
//use myAwesomeService, get the data and output
if($scope.dataSource ==='database') {
return //perform operation based on 'database'
}
else if($scope.dataSource ==='text') {
return //perform operation based on 'text'
}
else if($scope.dataSource ==='csvfile') {
return //perform operation based on 'csvfile'
}
else if($scope.dataSource ==='form') {
return //perform operation based on 'form'
}
}
}]);
Questions:
How can polymorphism be generally achieved in Javascript? In JavaScript, achieving polymorphism may not have established best practices. Personally, I typically rely on interfaces by implementing dependency injection and passing objects that conform to the same interface. By calling a shared method from the controller, I maintain flexibility without getting involved in specific implementation details.
How should this be implemented using AngularJS? Is there a standard Angular way of implementing polymorphism? Can you provide a conventional approach to achieving polymorphism in AngularJS?