I used *ngIf to judge the array length in html
<div *ngIf="apps.length === 0">
and define the apps in .ts file
public apps: any[];
and apps was retrieved from the rest api data:
ngOnInit() {
const refSpinner = this._simsSpinnerService.showSpinner('my-apps-spinner');
const getMyApps = this._myAppsService.getMyApps().pipe(share(), finalize(() => { this._simsSpinnerService.stopSpinner(refSpinner); }))
this._subscriptions.push(getMyApps.subscribe({
next: (data) => {
if (data && data instanceof Array) {
debugger
this.apps = data;
}
},
error: (err) => MessageService.addError(err)
}));
}
The console will print error message:
ERROR TypeError: Cannot read properties of undefined (reading 'length')
at MyAppsComponent_Template (my-apps.component.html:13:30)
I add debugger and found the this.apps is undefined before the data was assigned to it.
Then I changed the way to init data type like:
public apps = [];
And the error was disappeared, found that this.apps is an array before the data was assigned to it.
I searched and found that
any[] is an array where the item is of type any.
But why is it undefined? Shouldn't it be a array of any elements in it?
CodePudding user response:
I believe this is because the original code used a declaration, while the update code has initialization.
Declaration
Declaration tells the compiler the variable name and type. It does not give the variable a value (or rather, it gives it undefined
). In other words, it declares what the variable is.
public apps: any[]; // apps = undefined
Initialization
To actually give the variable a value other than undefined
, we have to initialize it.
public apps = []; // apps = []
The compiler can then infer the type of the variable apps
, which is, in this case, Array<any>
This alone isn't enough to explain why the compiler errors, however. Because you can keep a variable uninitialized as long as you give it a value later. However, you attempt to read the variable's length with <div *ngIf="apps.length === 0">
, which results in an error (as undefined
has no property length
)