能够以json格式读取对象,但无法在Angular2中读取其属性

时间:2017-12-07 18:42:35

标签: angular typescript object

Error image
我能够以json格式访问该对象,我可以看到所有属性和值,但我无法访问各个属性值。

我非常感谢你提前帮助!!!

 example.html 

<label>Name:</label>

<input type="text" [(ngModel)]="yourName" placeholder="Enter a name here">
<input type="number" [(ngModel)]="age" placeholder="Enter age here">
<br>
<button (click)="send({ name : yourName, age : age})">send</button>

<h1 [hidden]="!yourName">Hello {{yourName}}!</h1>
{{myobj | json}}
{{myobj.name}}




example.ts

import {Component} from 'angular2/core';

@Component({
 selector: 'hello-world',
 templateUrl: 'src/hello_world.html'
})
export class HelloWorld {
yourName: string = '';
myname : string;
myage : number;
send : any (obj){
  console.log(obj);
  this.myobj = obj;
}

}

1 个答案:

答案 0 :(得分:0)

以下代码适用于我。我刚刚在组件中定义了myobj:any并修改了send方法签名。

hello_world.html

    <label>Name:</label>
    <input type="text" [(ngModel)]="yourName" placeholder="Enter a name here">
    <input type="number" [(ngModel)]="age" placeholder="Enter age here">
    <br>
    <button (click)="send({ name : yourName, age : age})">send</button>

    <h1 [hidden]="!yourName">Hello {{yourName}}!</h1>
    {{myobj | json}} 
    {{myobj.name}}

helloworld.ts

import {Component} from '@angular/core'

@Component({
 selector: 'hello-world',
 templateUrl: 'src/hello_world.html'
})
export class HelloWorld {
yourName: string = '';
myname : string;
myage : number;
myobj:any;

constructor(){}

public send(obj:any):void{
  console.log(obj);
  this.myobj = obj;
}


}

这是一个工作的plunker的链接

https://plnkr.co/edit/5eNU8ermOX90UThetAJX?p=preview