I am working on creating a form in Angular, and I need some placeholder data to fill in the form fields. This data is fetched from a service as JSON with three specific fields.
Due to my limited understanding of TypeScript, I may be making a basic mistake in my code. Here's what I have so far:
export class Component{
public data:{
id: string,
quantity: number,
ref: string
};
constructor(private service: Service){
this.data = this.service.getDataById(id) // I get the id from somewhere else
}
ngOnInit(): void {}
form = new FormGroup({
id: new FormControl(this.data.id, Validators.required),
ref: new FormControl(this.data.ref, Validators.required),
quantity: new FormControl(this.data.quantity, Validators.required),
})
}
In addition, here is the service I am using:
export class service{
/* @ngInject */
constructor(private http: HttpClient) {}
getDataById(id: number): Observable<{
id: string;
quantity: number;
ref: string;
}> {
return this.http.get<{
id: string;
quantity: number;
ref: string;
}>(`api/getOfById/${id}`);
}
}
Although I know that my API returns the necessary JSON response with the three specified fields:
{
creationTimestamp: /*the time*/,
data:{
id: /*value*/,
quantity: /*value*/,
ref: /*value*/
}
}
Initially, I encountered an error because my service returns an Observable
. So, I modified my data
variable to be:
public data: Observable<{
id: string;
quantity: number;
ref: string;
}>;
However, another issue surfaced upon referencing this.data.id
:
TS2729: Property 'data' is used before its initialization.
This confuses me since I do initialize the data in my constructor. What could I be missing here? How can I successfully retrieve the JSON data into the data
property of my component?
Update:
I have made changes according to Yong Shun's suggestion:
export class Component{
data: { id: string; quantity: number; ref: string };
constructor(
private service: Service
) {
this.service
.getDataById(id)
.subscribe((value) => {
this.data = value;
});
}
//...
}
Despite these updates, the same error regarding this.data.id
persists:
TS2729: Property 'data' is used before its initialization.
Further Update:
Following Yong Shun's advice, my current implementation looks like this:
export class Component {
data!: { id: string; quantity: number; ref: string };
constructor(
private service: Service
) {}
ngOnInit(): void {
this.service
.getDataById(id)
.subscribe((value) => {
this.data = value;
});
}
form = new FormGroup({
id: new FormControl(this.data.id, Validators.required),
ref: new FormControl(this.data.ref, Validators.required),
quantity: new FormControl(this.data.quantity,Validators.required),
})
}
Now, I encounter a different error:
TypeError: Cannot read properties of undefined (reading 'id')