Issue
I'm trying to make a simple application with ionic (angular)
my problem is : Cannot set property 'origin' of undefined
this is the interface Product.ts
export interface Products{
id: number;
new: boolean;
origin: string;
branch: string;
product: string;
quantity: string;
productId: string;
Detail_product: string;
Installed: boolean;
}
and here the ts code :
ngOnInit() {
this.makeObject("03-2-450-2");
}
makeObject(qrcode) {
let obj: Products ;
let Qrstring: string = qrcode;
obj.origin! = Qrstring.substring(0, Qrstring.indexOf("-"));
console.log(obj.origin);
}
}
Solution
obj
is never assigned to anything. It is only given a type. You have to use e.g. let obj: Products = {};
.
Then you will have the problem, that all the properties of obj
are undefined.
It would be better to assing it as you go. Example:
let Qrstring: string = qrcode;
let obj: Products = {
origin: Qrstring.substring(0, Qrstring.indexOf("-")),
// set the other required properties
};
obj.origin! = Qrstring.substring(0, Qrstring.indexOf("-"));
Note: if you don't need all properties you can mark them as optinal in the template with the questionmark operator. Example Installed: boolean;
see: https://stackblitz.com/edit/typescript-tmupfv
You can then cast it with let obj: Products = {} as unknown as Products;
(very hacky, may lead to problems later on)
Answered By - Stefan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.