How to update a service collection by calling index a second service?

Asked

Viewed 22 times

1

In the call of a service within my controller I carry little data, and as soon as this data is loaded, on the screen, behind should come the complete data for a particular filtered item, the requests are occurring, the second being a little slower, exactly as it should be, the problem is not there. It is in the rewrite of the Scope collection variable, which is not updated in the view: $scope.data_collection. I made a small minimalist example to sketch the problem:

$scope.data_collection = [];

MyFirstService.getData($scope) //passando $scope.all retorna uma API
    .then(function(firstResult){
    //seta poucos dados
    $scope.data_collection = firstResult;
    $scope.ids_update = firstResult.has_updated_ids;

    MySecondService.getData($scope) //passando $scope.ids_update retorna somente as ID que deverão completar a API
    .then(function(secondResult){
      console.log('carregaria dados completos para um determinado ID')
       /* no caso, eu resumi, e retirei o filtro daqui, 
         este filtro identificaria os índices 
         dos itens que deverão trazer outros dados novos, 
         como no exemplo abaixo (index = 2), 
         a coleção de índice 2 deveria ser atualizada, 
         porém não está acontecendo na minha view... 
       */

       $scope.data_collection[2] = secondResult[2];

    });   

});

console.log($scope.data_collection);

View:

 <div class="content-item pull-left" 
  ng-repeat="(key, item) in data_collection | filter:{category:filters.category}">
   <img ng-src="{{item.imagem}}" class="img-responsive">
   <h3>{{item.title}}</h3>
    <p>{{item.subtitle}}</p>
</div>
  • That second MySecondService.getData($scope) is called 1 per id or passes the missing ids all together? and what type is secondResult?

  • would be the Ids, example: $scope.ids_update = [120, 124, 130]; but the return of this is dealt with in the service layer.

2 answers

0


I sent the Ids to a callback method:

  CadernosService
   .getCadernosPage(data_set)
   .then(function (response) {
                            $('.loadingData').css({'bottom': '0', 'position':'fixed', 'top':'','margin-top': '369px'})
                                .addClass('filter-bg-loading');
                            $scope.isReaded = true;
                            $scope.next_page = true;
                            if (angular.isDefined(response.result)) {
                                if (response.result.length < $scope.qtd_per_page) {
                                    $scope.next_page = false;
                                }
                            }


                            parseDataDisplay(response, user_id, school_id, function (ids, user_id, school_id) {
                                var data_set_two = {
                                    fulldata: true,
                                    user_id: user_id,
                                    role: data_form.role,
                                    school_id: school_id,
                                    lista_de_cadernos: ids,
                                    editoria: null
                                };
                                CadernosService.getCadernosLista(data_set_two)
                                    .then(function (res) {
                                        completeDataDisplay(res);
                                    });
                            });

                            $scope.IsLoading = false;


                        }, function () {
                            $scope.IsLoading = false;

                        });
                };

     function parseDataDisplay(response, user_id, school_id, callback) {

                    var _self = this;
                    _self.dataCollectionDefault = $scope.my_collection;
                    var ids = [];

                    if (response.status) {
                        angular.forEach(response.result, function (value) {
                            ids.push(parseInt(value.ID));
                            var sampleDisplay = {
                                id: value.ID,
                                edition_id: value.edition_id,
                                title: value.title,
                                subtitle: value.subtitle,
                                imagem:value.imagem,

                                date_activity: value.data_op,
                                data_publicacao: value.data_publicacao,
                                status: value.status,
                                category: value.category,
                                atividades: [],
                                is_pro_valid:data_form.is_pro_valid,
                                displayItem: function () {
                                    $rootScope.displayItem(this, 'all');
                                },
                                is_loading: true,
                                fulldata: false,
                            };
                            _self.dataCollectionDefault.push(sampleDisplay);
                        });
                        $scope.my_collection = _self.dataCollectionDefault;

                        callback(ids, user_id, school_id);

                    }

                }


function completeDataDisplay(response) {

                var _self = this;

                if (response.status) {
                    //  console.log('READY FULLDATA');
                    $scope.ready_full = true;
                    for (var i in response.result) {
                        var value = response.result[i];
                        var index = $filter('FilterData')(value.ID, $scope.my_collection, 'id');
                        var completeDisplay = {
                            id: value.ID,
                            edition_id: value.edition_id,
                            title: value.title,
                            subtitle: value.subtitle,
                            title_text: value.title_text,
                            subtitle_text: value.subtitle_text,
                            slug_title: $scope.formatSlug(value.title),
                            imagem: value.imagem,
                            numero_edicao: value.number,
                            date_activity: value.data_op,
                            data_publicacao: value.data_publicacao,
                            status: value.status,
                            category: value.category,
                            is_loading: false,
                            fulldata: true,
                            is_pro_valid:data_form.is_pro_valid,
                            atividades: [
                                {
                                    id: value.activity_id1,
                                    points: value.pontos_obtidos_1,
                                    total_points: value.maxpontuation_activity_1,
                                    life_one: $scope.resultLifes(value.tentativas_atividade_1, 1),
                                    life_two: $scope.resultLifes(value.tentativas_atividade_1, 2),
                                    type: value.actype1,
                                    type_variation: value.actype_variation_1,
                                    indicacao: false,
                                    title: value.actitle1,
                                    description: '',
                                    descritores: value.descritores_activity_1
                                },
                                {
                                    id: value.activity_id2,
                                    points: value.pontos_obtidos_2,
                                    total_points: value.maxpontuation_activity_2,
                                    life_one: $scope.resultLifes(value.tentativas_atividade_2, 1),
                                    life_two: $scope.resultLifes(value.tentativas_atividade_2, 2),
                                    type: value.actype2,
                                    type_variation: value.actype_variation_2,
                                    indicacao: false,
                                    title: value.actitle2,
                                    description: '',
                                    descritores: value.descritores_activity_2
                                },
                                {
                                    id: value.activity_id3,
                                    points: value.pontos_obtidos_3,
                                    total_points: value.maxpontuation_activity_3,
                                    life_one: $scope.resultLifes(value.tentativas_atividade_3, 1),
                                    life_two: $scope.resultLifes(value.tentativas_atividade_3, 2),
                                    type: value.actype3,
                                    type_variation: value.actype_variation_3,
                                    indicacao: false,
                                    title: value.actitle3,
                                    description: '',
                                    descritores: value.descritores_activity_3
                                },
                                {
                                    id: value.activity_id4,
                                    points: value.pontos_obtidos_4,
                                    total_points: value.maxpontuation_activity_4,
                                    life_one: $scope.resultLifes(value.tentativas_atividade_4, 1),
                                    life_two: $scope.resultLifes(value.tentativas_atividade_4, 2),
                                    type: value.actype4,
                                    type_variation: value.actype_variation_4,
                                    indicacao: false,
                                    title: value.actitle4,
                                    descritores: value.descritores_activity_4
                                }
                            ],
                            displayItem: function () {
                                $scope.displayItem(this, 'all');
                            }
                        };

                        $scope.my_collection[index] = completeDisplay;
                        $scope.full_data = true;

                    }
                }

            }

0

I think you need to rewrite .data_collection to trigger Angular’s reactivity. Do a mapping where you add the extra information and then replenish everything and let Angular detect what needs to be modified in the DOM or not.

$scope.data_collection = [];

MyFirstService.getData($scope)
  .then(function(firstResult) {
    $scope.data_collection = firstResult;
    $scope.ids_update = firstResult.has_updated_ids;

    MySecondService.getData($scope)
      .then(function(secondResult) {
        $scope.data_collection = $scope.data_collection.map(item => {
          const index = $scope.ids_update.indexOf(item.id);
          return index != -1 ? secondResult[index] : item;
        });
      });
  });

  • Thank you for the reply, maybe it is the best way, I have not tested, but I will publish the way I had solved here.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.