2016-03-23 7 views
0

In einer Web-App habe ich zwei Felder mit einigen Elementen. Ich habe auch eine Seite mit Filtern (zusammengesetzt aus einer Auswahl). Zu Beginn sind die Filter alle ausgewählt und es funktioniert. Aber wenn ich eine Kombination versuche, die nichts in der ersten Liste findet, aber einige Daten in der zweiten Liste sind, habe ich einen Fehler bekommen. Dies ist das, wenn ich den Dienst in der Steuerung aufrufen:Angular Kann keine Eigenschaft von null lesen

if(data){ // If i have some response form serve 

var tmp = null; 
var lastName = null; 

angular.forEach(data.people, function(ppl){ 
if(ppl.lastName != lastName){ 
    if (lastName != null){ 
     $scope.people.push(tmp); 
    } 
    // Clean the tmp 
    tmp = { 
      name : null, 
      count : 0, 
      products : [] 
    }; 
    // Update lastName 
    lastName = ppl.lastName; 
    } 
    // Add the actual row in the ob 
    tmp.name = lastName; 
    tmp.count += ppl.personCount; 
    tmp.products.push(ppl); 
    }); 

    // Process lasts elements (if there are some) in the array 
    if(tmp.products.length > 0){ 
    $scope.people.push(tmp); 
    } 

Der Fehler ist: Cannot read property 'products' of null

Ich habe versucht zu schreiben: var tmp = []; statt null, aber es sagt Cannot read property 'products' of undefined

+1

Verwenden Sie 'if (tmp && tmp.products && tmp.products.length> length> 0)' für die letzte Verifizierung –

Antwort

0

Ich denke, Die angular.forEach gibt Ihnen ein Problem mit dem Scoping. Probieren Sie stattdessen den folgenden Code aus.

if(data && data.people.length > 0){ // If i have some response form serve 

var tmp = {}; 
var lastName = null; 

for(var i = 0; i < data.people.length; i++){ 
    if(ppl.lastName != lastName){ 
     if (lastName != null){ 
      $scope.people.push(tmp); 
     } 
     // Clean the tmp 
     tmp = { 
      name : null, 
      count : 0, 
      products : [] 
     }; 
     // Update lastName 
     lastName = ppl.lastName; 
    } 
    // Add the actual row in the ob 
    tmp.name = lastName; 
    tmp.count += ppl.personCount; 
    tmp.products.push(ppl); 
    }; 

    // Process lasts elements (if there are some) in the array 
    if (tmp && tmp.products && tmp.products.length > 0) 
     $scope.people.push(tmp); 
    } 
}