该图再次显示每个对象都有一个原型.构造函数Foo也有自己
__proto__的Function.prototype,它又通过其__proto__属性再次引用到Object.prototype.因此,重复,Foo.prototype只是Foo的一个显式属性,它指的是b和c对象的原型.
var b = new Foo(20);
var c = new Foo(30);
Run Code Online (Sandbox Code Playgroud)
__proto__和prototype属性有什么区别?

这个数字来自这里.
javascript prototype prototypal-inheritance javascript-objects
我从远程REST服务器读取了一个JSON对象.此JSON对象具有typescript类的所有属性(按设计).如何将收到的JSON对象强制转换为类型var?
我不想填充一个typescript var(即有一个带有这个JSON对象的构造函数).它很大并且通过属性按子对象和属性跨子对象复制所有内容将花费大量时间.
更新:您可以将其转换为打字稿界面!
有人可以提供一个简单的例子来演示实现装饰器的正确方法,并描述可能的有效装饰器签名中的参数是什么意思吗?
declare type ClassDecorator = <TFunction extends Function>(target: TFunction) => TFunction | void;
declare type PropertyDecorator = (target: Object, propertyKey: string | symbol) => void;
declare type MethodDecorator = <T>(target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<T>) => TypedPropertyDescriptor<T> | void;
declare type ParameterDecorator = (target: Function, propertyKey: string | symbol, parameterIndex: number) => void;
Run Code Online (Sandbox Code Playgroud)
另外,在实现装饰器时是否应该记住哪些最佳实践注意事项?
我做了很多研究,但我对我发现的东西并不完全满意.只是为了确定这是我的问题:什么是将JSON反序列化为TypeScript运行时类实例的最强大,最优雅的自动化解决方案?
说我上了这堂课:
class Foo {
name: string;
GetName(): string { return this.name };
}
Run Code Online (Sandbox Code Playgroud)
并说我有这个JSON字符串用于反序列化:
{"name": "John Doe"}
Run Code Online (Sandbox Code Playgroud)
获取名称设置为"John Doe"和GetName()方法的Foo类实例的最佳和最易维护的解决方案是什么?我非常具体地问,因为我知道很容易反序列化为纯数据对象.我想知道是否可以使用工作方法获取类实例,而无需进行任何手动解析或任何手动数据复制.如果无法实现全自动化解决方案,那么下一个最佳解决方案是什么?
我有一个简单的登录方案,要求用户在Typescript中输入电子邮件和密码.我需要创建一些类型来获得强类型并将其发送到后端.
应该写成:
export interface UserLogin {
email: string;
password: string;
}
//OR
export class UserLogin {
email: string;
password: string;
}
Run Code Online (Sandbox Code Playgroud)
以及如何知道何时使用这些方案?
我遇到以下代码的问题.
它基本上应该做什么.它应该加载和解析给定的JSON文件.在RequestListender中,它应该显示Product.ts中方法返回ID的字符串和字符串.在正确显示的地方,该方法失败并出现下述错误.HelloToString()tProduct.IdtProduct.ToString()
非常感谢提前.
错误信息:
TypeError: tProduct.ToString is not a function.
(In 'tProduct.ToString()', 'tProduct.ToString' is undefined)
Run Code Online (Sandbox Code Playgroud)
文件:Test.ts
var currentProduct = null as pvis.Product;
function runTest(path) {
var request = new XMLHttpRequest();
request.onload = loadRequestListener;
request.open("get", path, true);
request.send();
}
function loadRequestListener () {
var tProduct : pvis.Product = JSON.parse(this.responseText);
if (tProduct.Id) {
currentProduct = tProduct;
alert('loaded with Id: ' + tProduct.Id );
alert('loaded with Content: ' + tProduct.ToString() );
}
else {
alert('product …Run Code Online (Sandbox Code Playgroud) 我一直在关注Angular2入门文档,让我自己的应用程序开始,我已经成功地从本地文件中检索JSON对象并在angular2模板中显示它们.但是目前它依赖于与我的JSON文件中的对象结构完全匹配的角度类.
最终我需要我的应用程序使用JSON-LD,它具有诸如"@id"的属性名称.我做了一些谷歌搜索,似乎RxJS可能有我正在寻找的功能,但我不知道从哪里开始中断自动绑定从一些JSON数据直接到我的angular2类,而是能够看到在json中标记为"@id"的东西并设置SomeClass.id的值
当前代码自动生成Person类的数组:
getPeople(){
return this._http.get(this._peopleUrl)
.map(response => <Person[]> response.json().data)
.do(data => console.log(data)) //debug to console
.catch(this.handleError);
}
Run Code Online (Sandbox Code Playgroud)
这样的JSON很好:
[
{
"id":"1",
"name":"tessa"
},
{
"id":"2",
"name":"jacob"
}
]
Run Code Online (Sandbox Code Playgroud)
但是对于这样的JSON来说显然会失败:
[
{
"@id":"1",
"name":"tessa"
},
{
"@id":"2",
"name":"jacob"
}
]
Run Code Online (Sandbox Code Playgroud)
我的课很简单(目前:-))
export class Person {
constructor(
public id:number,
public name:string,
){}
}
Run Code Online (Sandbox Code Playgroud)
任何人都可以指出我正确的方向为一些文件/例子将复杂/棘手的json映射到angular2中的类?
在创建模型驱动模板Reactive表单时,我从Form Value创建模型对象时.然后模型对象失去其TYPE.
对于一个简单的例子:
模特班书:
export class Book {
public name: string;
public isbn: string;
}
Run Code Online (Sandbox Code Playgroud)
零件:
@Component({
selector: 'app-book',
templateUrl: './book.component.html',
styleUrls: ['./book.component.css']
})
export class BookComponent implements OnInit {
bookFormGroup: FormGroup;
private newBook: Book = new Book();
constructor(private fb: FormBuilder) {
this.bookFormGroup = this.fb.group({
name: new FormControl(''),
isbn: new FormControl('')
});
}
ngOnInit() {
}
addBook() {
console.log('submit');
this.newBook = <Book> this.bookFormGroup.value;
console.log(this.newBook instanceof Book);
console.log(this.newBook);
}
}
Run Code Online (Sandbox Code Playgroud)
HTML:
<form [formGroup]="bookFormGroup" (ngSubmit)="addBook()">
<input type="text" formControlName="name" >
<input type="text" formControlName="isbn" …Run Code Online (Sandbox Code Playgroud) 我有几个Javascript原型.最初,实例将只填充ID,并为其他数据提供一些通用的占位符信息.然后我使用ID和对象类型(使用jQuery的AJAX函数)向服务器发送消息,服务器返回一个包含所有缺少信息(但没有ID)的JSON对象.返回对象中的变量与现有对象中的变量具有完全相同的名称.
将此转移到现有空对象的最简单方法是什么?我想出了一些替代方案
如果我使用第三个选项,这是正确的方法吗?:
for (var key in json) {
if (object.hasOwnProperty(key)) {
object[key] = json[key];
}
}
Run Code Online (Sandbox Code Playgroud)
假设json是返回的对象并且object是现有对象.
我在TypeScript中有以下小类,其中一些公共字段被装饰:
class Company {
@dataMember
public name: string;
@dataMember
public people: Person[];
}
class Person {
// ...
}
Run Code Online (Sandbox Code Playgroud)
通过使用反射元数据,我可以确定公司属性名称和人员的类型:它们分别是构造函数String和Array,它们是预期的和逻辑的.
我的属性装饰函数:
function decorate(target: Object, propertyKey: string | symbol): void {
var reflectType = Reflect.getMetadata("design:type", target, propertyKey);
// ...
}
Run Code Online (Sandbox Code Playgroud)
但是我如何确定数组元素的类型(构造函数)?它甚至可能吗?在上面的例子中,它应该是(引用)Person.
注意:我在实例化之前需要类型引用,因此,使用数组项动态确定类型是不可能的:没有数组项,甚至没有Array实例.
我从json文件上传数组.每1.5秒我检查文件是否有任何变化(目前我在一个文件上测试没有任何变化),但当我检查是否
if ( this.itemsParentArray[i] !== this.itemInArray[i] )
Run Code Online (Sandbox Code Playgroud)
它始终显示它不相等,并且console.log(""不等于")
我错过了代码中的内容吗?这里是:
export class HomeComponent {
itemsParentArray = [];
itemInArray = [];
myRes: Content;
showAssigned:boolean = false;
constructor(private structureRequest: StructureRequestService) {
setInterval(() => {
this.timerGetStructure();
}, 1500);
}
// using with setInterval to get new data and sets into content Array with this.updateItems(result) if it's new
timerGetStructure() {
this.structureRequest.sendRequest().subscribe((result) => this.updateItems(result));
}
updateItems(result) {
this.myRes = result;
this.itemInArray = this.myRes.content;
for ( let i = 0; i < this.itemInArray.length; i++) {
if ( …Run Code Online (Sandbox Code Playgroud) 处理http响应的Сommon方法是这样的:
return this._http.get(url)
.map((res: Response) => res.json());
Run Code Online (Sandbox Code Playgroud)
这提供了一个Observable<Object[]>其中Object被动态创建从JSON反序列化类型.然后你可以在*ngFor="let item of result | async"等等中使用这个结果......
我想获得一个特定的类型实例(意味着使用newoperator来调用类型的构造函数).尝试了不同的方法来实现这样的目标:
.map((res: Response) => { let obj = res.json(); return new MyObject(obj.id, obj.name);})
Run Code Online (Sandbox Code Playgroud)
但得到这个错误: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
这种方式似乎有效,但它过于复杂,可能无效:
.map((res: Response) => {
let results = <MyObject[]>[];
let obj = res.json();
obj.forEach(
function (o: any) {
results.push(new MyObject(o.id, o.name));
}
);
return results; …Run Code Online (Sandbox Code Playgroud) 我有JSON数组如下:
var json = [{
id: 1,
login: "Mieszko",
name: "Misztal",
surname: "Adminek",
phone: "0413414",
role: 2
},
{
id: 2,
login: "Rafal",
name: "Robak",
surname: "Kierowczek",
phone: "5145145",
role: 1
}
];
Run Code Online (Sandbox Code Playgroud)
我还创建了User类,如下所示:
export class User extends BaseModel {
id: number;
login: string;
name: string;
surname: string;
phone: string;
roles: Roles;
admin: boolean;
driver: boolean;
isDriver(): boolean {
return this.roles === 1;
}
//other methods
}
Run Code Online (Sandbox Code Playgroud)
我的计划是将命令JSON数组转换为User数组.在JSON内部,我获得了整数角色.我班上有管理员和驱动程序布尔字段.这在复选框的ngModel中是必需的.
现在问题出在这一行之后
var users: Array<User> = JSON.parse(JSON.stringify(json));
Run Code Online (Sandbox Code Playgroud)
我无法从User类调用方法,例如users[0].isDriver()因为编译器无法识别isDriver()方法.
有谁知道如何解决这个问题?
typescript ×9
json ×5
angular ×4
javascript ×3
decorator ×2
ajax ×1
angular-http ×1
arrays ×1
class ×1
function ×1
interface ×1
jquery ×1
jsonp ×1
prototype ×1
reflection ×1
rxjs ×1
undefined ×1
web ×1