簡體   English   中英

如何修復無法讀取 Angular 中未定義的屬性

[英]How to fix Cannot read property of undefined in Angular

我從 JSON 中的 spring 服務器獲取數據,數據恢復良好,但是當我嘗試在我的 Angular 組件中對它們進行 foreach 時,出現以下錯誤:無法讀取未定義的屬性事務

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);
   }
 }

這是我的 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");
  }
}

這是我的解析器:

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

  constructor(private affaires: AffaireService) {}

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

編輯 :

這是我的 listeAffaires 變量的內容:

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

我和你有同樣的問題,我試圖迭代 Spring DATA 返回的對象,其中當然包括 _embedded。 在我的情況下,我使用了 foreach 但在 ngOnInit() 內部,我得到了同樣的錯誤。

解決方案是將 foreach 放在 subscribe() 函數中並在 ngOnInit() 中調用該函數,我不知道為什么會發生這種情況,但這與同步和異步函數有關。

我希望有一天這會對某人有所幫助。

編輯:這是打字稿代碼:

我從后端獲取數據,然后將其存儲在對象汽車中,並在同一個 subscribe() 方法中遍歷汽車。_embedded.cars 並將 id 和模型存儲在數組 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); } );

  }

然后你只需在 ngOnInit() 中調用該方法,這樣你就可以確保this.cars._embedded.cars不會是 Undefined 。


  ngOnInit(): void {

    this.onGetCars();

  }

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

}

添加我上面建議的檢查應該可以解決您的問題

嘗試使用paramMapget獲取路由變量:

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

要將參數讀取為 observable:

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

更新:

如果要遍歷參數:

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

在我看到你的代碼的最后一部分(JSON 響應)后,我的印象是你應該遍歷this.listeAffaires.affaires而不是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);
   }
 }

編輯

這是一個示例,它正在做與您正在嘗試的相同的事情。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM