I work on angular 13 application I face issue when declare variable of type model .
error Property has no initializer and is not definitely assigned in the constructor
error happen when declare items variable for type model itemData as below :
items:ItemsData[]
model items data
export interface ItemsData {
id:number;
itemNameER:string;
itemNameEN:string;
description:string;
}
component.ts
export class ItemsComponent implements OnInit {
items:ItemsData[];
constructor(private erpservice:ErpServiceService) { }
retrieveAllItems(pageNumber: number = 0): void {
this.erpservice.getAll(pageNumber)
.subscribe(
data => {
this.items=data.items;
console.log(data);
});
}
}
I need to recieve result returned from function retrieveAllItems
on itemsData model i created but it give me error .
so How to solve issue and why this issue happen ?
updated post
i still have issue when get result of retrieveAllItems
function on this line
this.items=data.items;
property items doesnot exist on type itemdata
so what i do to solve this issue ?
console.log(data);
data returned as below :
{
"items": [
{
"id": 3,
"itemNameEN": "pen"
},
{
"id": 4,
"itemNameEN": "pencil"
},
{
"id": 5,
"itemNameEN": "pen2"
}
],
"pager": {
"numberOfPages": 1,
"currentPage": 1,
"totalRecords": 3
}
}
service.ts
getAll(pageNumber: number): Observable<ItemsData> {
let params = new HttpParams();
if (pageNumber)
params = params.append('pageNumber', pageNumber);
let httpOptions = {
params: params
};
return this.http.get<ItemsData>(baseUrl,httpOptions);
}
CodePudding user response:
About your first issue
It occurs because you have not initialized items
with a value.
There are several options on how to solve the issue:
items: ItemsData[] = []; // Initialization with an empty array
items?: ItemsData[]; // Declaration as an optional variable
items!: ItemsData[]; // Declaration as non-nullable which basically corresponds to 'items: ItemsData[] = undefined'
About your second issue
According to your method signature getAll()
returns Observable<ItemsData>
, but this does not correspond to the json-response you showed me. It actually returns something like Observable<DataWrapper>
and then you should define an additional model that looks like this:
export interface DataWrapper {
items: ItemsData[];
}
Then the service.ts would look like this:
getAll(pageNumber: number): Observable<DataWrapper> {
let params = new HttpParams();
if (pageNumber)
params = params.append('pageNumber', pageNumber);
let httpOptions = {
params: params
};
return this.http.get<DataWrapper>(baseUrl,httpOptions);
}