简体   繁体   中英

How to fix Cannot read property of undefined in Angular

I'm getting data from a spring server in JSON, data are well recovered, but when I try to make a foreach on them in my Angular component, I get the following error: Cannot read property Affaires of undefined

constructor(private serviceFam:FamillesService, private 
serviceAff:AffaireService, private router:Router, private route: 
ActivatedRoute) {
    this.listeFamilles = this.route.snapshot.data;
    this.listeAffaires = this.route.snapshot.data
    for(let a of this.listeAffaires._embedded.affaires){
      console.log(a.sn);
   }
 }

Here is the call of my API :

//Connexion avec le serveur
export class AffaireService {

  public host: string="http://localhost:8080";

  constructor(private httpClient:HttpClient) {}

  public getAllAffaires(){
    return this.httpClient.get(this.host+"/affaires");
  }
}

And here is my resolver :

@Injectable()
export class AffairesResolver implements Resolve<Affaire> {

  constructor(private affaires: AffaireService) {}

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): any {
    return this.affaires.getAllAffaires();
  }
}

EDIT :

Here is the content of my listeAffaires variable :

affaire:
page:
number: 0
size: 20
totalElements: 118
totalPages: 6
__proto__: Object
_embedded:
affaires: Array(20)
    0: {id: 1, sn: "A129B", zc: null, certificat: null, etat: false, …}
1: {id: 2, sn: "1196M", zc: null, certificat: null, etat: false, …}
2: {id: 3, sn: "784M", zc: null, certificat: null, etat: false, …}
3: {id: 4, sn: "565M", zc: null, certificat: null, etat: false, …}
4: {id: 5, sn: "B161B", zc: null, certificat: null, etat: false, …}
5: {id: 6, sn: "A446B", zc: null, certificat: null, etat: false, …}
6: {id: 7, sn: "862M", zc: null, certificat: null, etat: false, …}
7: {id: 8, sn: "1594", zc: null, certificat: null, etat: false, …}
8: {id: 9, sn: "B112B", zc: null, certificat: null, etat: false, …}
9: {id: 10, sn: "40080", zc: null, certificat: null, etat: false, …}
10: {id: 11, sn: "A704B", zc: null, certificat: null, etat: false, …}
11: {id: 12, sn: "869M", zc: null, certificat: null, etat: false, …}
12: {id: 13, sn: "B069B", zc: null, certificat: null, etat: false, …}
13: {id: 14, sn: "930B", zc: null, certificat: null, etat: false, …}
14: {id: 15, sn: "1698", zc: null, certificat: null, etat: false, …}
15: {id: 16, sn: "287B", zc: null, certificat: null, etat: false, …}
16: {id: 17, sn: "B887B", zc: null, certificat: null, etat: false, …}
17: {id: 18, sn: "C875B", zc: null, certificat: null, etat: false, …}
18: {id: 19, sn: "A747B", zc: null, certificat: null, etat: false, …}
19: {id: 20, sn: "118BTC", zc: null, certificat: null, etat: false, …}
length: 20
__proto__: Array(0)
__proto__: Object
_links: {first: {…}, self: {…}, next: {…}, last: {…}, profile: {…}}
__proto__: Object

I had the same problem as you, i was trying to iterate over an object returned by Spring DATA, which of course included the _embedded. In my case I used foreach but inside the ngOnInit() and i got the same error.

The SOLUTION is to put the foreach inside a subscribe() function and call that function inside ngOnInit(), I don't know why this happens but it has something to do with synchronous and asynchronous functions.

I hope this would help someone someday.

Edit : Here is the typescript code :

I get the Data from backend, then I store it in the object cars, and in the same subscribe() method I iterate over cars._embedded.cars and store the id and modele in an Array dropdownCars.


dropdownCars = [];
public cars: any = {} ;

onGetCars(){
    this.bankservice.getCars()
      .subscribe(data => {
        this.cars = data;

        this.cars._embedded.cars.forEach(element => {
          this.dropdownCars.push(
                                  {id: element.id , 
                                   modele: element.modele});
        });
        
    }, err => { console.log(err); } );

  }

Then you just call the method in ngOnInit() and this way you make sure this.cars._embedded.cars won't be Undefined .


  ngOnInit(): void {

    this.onGetCars();

  }

 for(let a of this.listeAffaires._embedded.affaires){
      if(this.listeAffaires._embedded.affaires) console.log(a.sn);

}

Adding checks like I suggested above should fix your problem

Try to use paramMap and get to get route variables:

let id = this.route.snapshot.paramMap.get('id');

To read parameters as observables:

this.route.paramMap
      .subscribe(params => {
          let id = params.get('id');
          console.log(id);
      });

UPDATE:

If you want to iterate through parameters:

this.route.paramMap
      .subscribe(params => {
          for (let key in params) {
            if(params.hasOwnProperty(key)) {
                console.log(key + ": " + params[key]);
            }
          }
      });

After I saw the last part of your code (the JSON response), I'm left under the impression that you should iterate through the this.listeAffaires.affaires not through the this.listeAffaires._embedded.affaires .

constructor(private serviceFam:FamillesService, private 
serviceAff:AffaireService, private router:Router, private route: 
ActivatedRoute) {
    this.listeFamilles = this.route.snapshot.data;
    this.listeAffaires = this.route.snapshot.data
    for(let a of this.listeAffaires.affaires){
      console.log(a.sn);
   }
 }

Edit

Here is a sample that is doing the same thing that you are trying.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM