I searched in Google/Github/Stackoverflow about this error but I am not able to fix this. I hope someone can help with a fix or suggestion
I have updated Angular project from v9 to v10, and after the update i got errors like the followwing, in a couple of modules.
Property 'searchParameters' is used before its initialization.
address: this.searchParameters?.address,
And the code in short:
export interface PartnerSearchParameters {
name?: string;
code?: string;
address?: string;
taxRegNumber?: string;
}
@Component({
selector: 'app-partner-search-list',
templateUrl: './partner-search-list.component.html',
styleUrls: ['./partner-search-list.component.scss']
})
export class PartnerSearchListComponent implements OnInit, AfterViewInit {
searchParameters: PartnerSearchParameters;
modelMainFilters = {
address: this.searchParameters?.address,
code: this.searchParameters?.code,
name: this.searchParameters?.name
taxRegNumber: this.searchParameters?.taxRegNumber ,
};
constructor(...){}
ngOnInit(): void {...}
...
}
The searchParameters is defined before the modelMainFilters, where i want to use ..
So I don’t understand at all where I should define it to be good.
Any suggestion?
CodePudding user response:
The error is clear, properties of searchParameters
are attempted to be used before it's initialized.
One solution is to initialize it with some values
searchParameters: PartnerSearchParameters = {
name: '',
code: '',
address: '',
taxRegNumber: ''
}
Or better yet, initialize the modelMainFilters
only after the searchParameters
are initialized
export class PartnerSearchListComponent implements OnInit, AfterViewInit {
searchParameters: PartnerSearchParameters;
modelMainFilters: PartnerSearchParameters;
ngOnInit(): {
this.someFunc().subscribe(res => { // <-- example
this.searchParameters = res;
this.modelMainFilters = this.searchParameters;
});
}
}
CodePudding user response:
You can use non-null assertion operator like this:
export interface PartnerSearchParameters {
name?: string;
code?: string;
address?: string;
taxRegNumber?: string;
}
@Component({
selector: 'app-partner-search-list',
templateUrl: './partner-search-list.component.html',
styleUrls: ['./partner-search-list.component.scss']
})
export class PartnerSearchListComponent implements OnInit, AfterViewInit {
searchParameters!: PartnerSearchParameters;
modelMainFilters = {
address: this.searchParameters?.address,
code: this.searchParameters?.code,
name: this.searchParameters?.name,
taxRegNumber: this.searchParameters?.taxRegNumber
};
constructor(...){}
ngOnInit(): void {...}
...
}
Keep in mind doing this you will end up with all properties of modelMainFilters
equal to undefined
like this:
modelMainFilters: {
address: undefined,
code: undefined,
name: undefined,
taxRegNumber: undefined
}