簡體   English   中英

Angular 10 錯誤類型錯誤:無法設置未定義的屬性(var)

[英]Angular 10 ERROR TypeError: Cannot set property (var) of undefined

在 AngularJS 中使用了很長時間后,我現在才開始學習 Angular 10。 我有這個代碼的工作版本,它沒有設置排序變量,但我使用這段代碼來了解為什么我不能在 sortById 函數中設置排序變量。 下面的代碼在第 29 行產生錯誤:錯誤類型錯誤:無法設置未定義的屬性“已排序”。

顯然我不明白這個。 Angular 框架中的概念。

 import { Component, OnInit } from '@angular/core';
 import { APPLICATIONS } from '../mock-applications';


 @Component({
   selector: 'app-applications',
   templateUrl: './applications.component.html',
   styleUrls: ['./applications.component.scss'],
 })

 export class ApplicationsComponent {

     data = APPLICATIONS;  
     sorted:number = 0;

     constructor() {};

     ngOnInit() {};

     // this function is triggered onClick 
     sortById(){
         // not sorted yet
         if(this.sorted === 0 || this.sorted === 2 ){
             this.data.sort(function (a, b) {
                  this.sorted = 1; // ERRROR HERE
                  console.log('asc');
                  return a.Id - b.Id;
             });
         // sorted 
         } else {
               this.data.sort(function (a, b) {
                    this.sorted = 2;
                    console.log('desc');
                    return b.Id - a.Id;
               });
         }
    
         console.log('sorted ' + this.sorted);
     }

}

         // not sorted yet
         if(this.sorted === 0 || this.sorted === 2 ){
             this.data.sort(function (a, b) { <--------- loss of scope
                  this.sorted = 1; // ERRROR HERE
                  console.log('asc');
                  return a.Id - b.Id;
             });
         // sorted 
         }

以這種方式聲明函數會失去封閉范圍,在這種情況下, this可能指向函數實例(它可能是窗口。有趣!)。 如果您使用箭頭函數,您將引入/綁定到組件的封閉范圍。

 if(this.sorted === 0 || this.sorted === 2 ){
             this.data.sort((a, b) => { <--------- arrow function
                  this.sorted = 1; // ERRROR HERE
                  console.log('asc');
                  return a.Id - b.Id;
             });
         // sorted 
         }

這是一個很好的入門,可以更好地理解范圍https://medium.com/javascript-in-plain-english/everything-you-wanted-to-know-about-javascript-scope-e991a8288bc

暫無
暫無

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

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