Hello I have a small problem to understand Typescript and how to create a Object with properties.
I dont't understand how I can create a Object and after creation add some values in it.
I read many blogs with possible solutions but nothing worked. All I get is "Cannot set property 'bookTitle' of undefined".
I already tried this solutions. TypeScript and field initializers
How can I create an object based on an interface file definition in TypeScript?
In Typescript how to fix Cannot set property 'first' of undefined
At least I know that I have not fully understand how Typescript works and how I should fix it. It is a little bit frustrating to learn this language. I have only experience in Java...
My example code
//one ts file
export interface Book {
bookTitle: string;
currentStatus: string;
daysLeft: number;
preregistrationStatus: string;
returnDate: string;
signature: string;
}
export class Lib {
books: Array<Book>;
ionViewDidLoad(): void {
this.getBorrowedBooks();
}
getBorrowedBooks(): void {
this.api.get('library/borrowedbooks')
.map(res => res.json())
.subscribe(
data => {
for ( let _i: number = 0; _i < data.length; _i++) {
this.metaInfo.set( data[_i].bookTitle, data[_i].daysLeft);
var book: Book = {
bookTitle: data[_i].bookTitle,
currentStatus: data[_i].bookTitle,
daysLeft: data[_i].bookTitle,
preregistrationStatus: data[_i].bookTitle,
returnDate: data[_i].bookTitle,
signature: data[_i].bookTitle,
};
this.books.push(book);
}
}
//Edit
Response Body
[
{
"bookTitle": "Mobile computing / Fuchß, Thomas , 2009 ",
"returnDate": "2018-03-04",
"currentStatus": "2. Verlängerung ",
"signature": "2009 A 3032;h",
"daysLeft": 21,
"preregistrationStatus": ""
}
]
export intefacelibrary/borrowedbooks. Do you have an example of the response?data[_i]at the beginning of each iteration of theforloop and verify thatdata[_i]is the value you expect? The error message seems to indicate thatdata[_i]might beundefinedin one of the loops.