admin管理员组文章数量:1425997
I'm trying to add an object array to an array in TypeScript (for an Angular 2 app). Here's a stripped down and simplified version of my code:
mylist.ts:
export class myList {
constructor(
Number1: number,
String1: string
){}
}
mylistponent.ts:
import { myList } from './myList';
export class ProductDetailComponent {
myNumber: number;
myString: string;
myList: Array<myList>;
constructor() {
this.myNumber = 10;
this.myString = "some text";
}
addNavigation() {
this.myList = [ new myList(this.myNumber, this.myString) ];
console.log(JSON.stringify(this.myList));
}
}
Output:
[{}]
What am I doing wrong?
I'm trying to add an object array to an array in TypeScript (for an Angular 2 app). Here's a stripped down and simplified version of my code:
mylist.ts:
export class myList {
constructor(
Number1: number,
String1: string
){}
}
mylist.ponent.ts:
import { myList } from './myList';
export class ProductDetailComponent {
myNumber: number;
myString: string;
myList: Array<myList>;
constructor() {
this.myNumber = 10;
this.myString = "some text";
}
addNavigation() {
this.myList = [ new myList(this.myNumber, this.myString) ];
console.log(JSON.stringify(this.myList));
}
}
Output:
[{}]
What am I doing wrong?
Share Improve this question asked Jun 2, 2016 at 8:27 I_LIKE_FOOI_LIKE_FOO 2,8743 gold badges19 silver badges18 bronze badges 1-
myList
is an object, not an array, this is expected behaviour – Robin-Hoodie Commented Jun 2, 2016 at 8:29
2 Answers
Reset to default 4You're not binding to a property of MyList
thus your object is empty.
Change your class to the following
export class myList {
constructor(
public Number1: number,
public String1: string
){}
}
By adding public
or private
TypeScript will create properties for you.
Now the result will be:
[{Number1: val, String1: val}]
You never set properties of the myList object in its constructor. Try this:
export class myList {
constructor(Number1: number, String1: string) {
this.number = Number1;
this.string = String1;
}
}
本文标签: javascriptArray of Arrays in TypeScriptStack Overflow
版权声明:本文标题:javascript - Array of Arrays in TypeScript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745463827a2659442.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论