Still confused about the services and factories of angularjs

I read several topics about angularjs services and factories. I understand that services are singletones, while factories return instances of objects. But I still do not understand how to use them. My application is a simple social network. The person using the application must be logged in, then they will be able to view other participants and send them messages.

My perfect design:

  • Create a Member object to represent an arbitrary member of my service. Whenever the "list" or "get" operation returns data, it must be wrapped in this element so that I can call the utility methods on it. I would use factory for this.
  • When a user enters the application, create an element that will represent them (containing their user ID and authentication token for future authenticated requests). This should be accessible to other areas, so they can either be bound to $ rootScope, or be a MemberService that returns an instance of an element adapted for an authenticated user.

I created the following:

angular.module('myapp.models', [])
.factory('Member', ['$log', 'DataService', '$http', 'Restangular',
    function($log, DataService, $http, Restangular) {
        return {
            user_id: null,
            first_name: null,
            last_name: null,

            authenticate: function(username, password, loginSuccessHandler, loginErrorHandler) {
                $log.debug("inside Member.authenticate");

                var authSuccessHandler = function(data, status, headers, config) {
                    $http.defaults.headers.common.Authorization = 'Basic ' + btoa(data._id + ':' + data.token);
                    var token = btoa(data._id + ':' + data.token);
                    user_id = data._id;       // attach this to the rootScope? Needs to be
                                              // globally accessible (or even this whole object)
                    Restangular.setDefaultHeaders({'Authorization': 'Basic ' + token});
                    $log.debug("Auth successful, token stored " + token);
                    loginSuccessHandler();
                };

                DataService.authenticate(username, password, authSuccessHandler, authErrorHandler);
            },
      ...

How can I create an instance of this object and make it accessible to other areas (for example, in other areas that I would know in the input user ID)?

Also, how can I instantiate this object when I parse the list of participants? For instance. if I have an object {first_name: "John", last_name: "Smith"}, how can I get a Member object from this factory with the specified attributes?

+4
2

factory service provider.

, angular :

function provider(name, provider_) {
    if (isFunction(provider_) || isArray(provider_)) {
        provider_ = providerInjector.instantiate(provider_);
    }
    if (!provider_.$get) {
        throw Error('Provider ' + name + ' must define $get factory method.');
    }
    return providerCache[name + providerSuffix] = provider_;
}

(singleton), angular . $get . provider ( angular docs):

myApp.provider('unicornLauncher', function UnicornLauncherProvider() {
  var useTinfoilShielding = false;

  this.useTinfoilShielding = function(value) {
    useTinfoilShielding = !!value;
  };

  this.$get = ["apiToken", function unicornLauncherFactory(apiToken) {

    // let assume that the UnicornLauncher constructor was also changed to
    // accept and use the useTinfoilShielding argument
    return new UnicornLauncher(apiToken, useTinfoilShielding);
  }];
});

. module.config(), , // , singleton, $get.

myApp.config(["unicornLauncherProvider", function(unicornLauncherProvider) {
  unicornLauncherProvider.useTinfoilShielding(true);
}]);

, , unicornLauncher, , $get , unicornLauncher , useTinfoilShielding = true .

, . -, singleton, , angular providerCache, . $get, .

: Singleton , , , .

, , . , , , , , .

factory. provider. , angular factory:

function factory(name, factoryFn) {
    return provider(name, { $get: factoryFn });
}

provider, , , , $get - , provider.

service:

function service(name, constructor) {
    return factory(name, ['$injector', function($injector) {
        return $injector.instantiate(constructor);
    }]);
}

factory, $get , angular, . , , , . , , , singleton-, .

, service - , angular , , factory - , , JavaScript.

, factory service.


.

factory, . , Member, :

var data = {first_name: "John", last_name: "Smith"} 
var member = new Member(data);

factory:

.factory('Member', ['$log', 'DataService', '$http', 'Restangular',
    function($log, DataService, $http, Restangular) {
        return function(data) {
        //construct the object
        }
])

new factory ( ) , , , JS. , . $rootScope , . , , .

+8

, Services , - .

: AngularJS: vs factory

0

Source: https://habr.com/ru/post/1536251/


All Articles