我有一个关于角度js 2的问题。 谁可以跟我说说如何从输入接收数据并返回json字符串?
这是我的代码:http-test.component.ts
<form action="POST">
UserName
<div>
<input type="text" required id= "username"/>
</div>
Password
<div>
<input type="password" required id= "password" />
</div>
Name
<div>
<input type="text" required id= "name"/>
</div>
<div>
<button type ="submit"> Submit</button>
</div>
</form>
`,
styles:[`
table tr:nth-child(even) {
background-color: #eeeeee;
}
`],
providers: [HttpTestService]
})
customers: Object;
constructor( private _httpService:HttpTestService){}
//Return Object json
onTestTable(){
this._httpService.getCurrentTime()
.subscribe(
customers => this.customers = customers.records
);
//On init when load page
ngOnInit(){
this.onTestTable();
}
}
这是代码服务:http-test.service.ts
constructor(private _http: Http) { }
getCurrentTime() {
return this._http.get('http://www.w3schools.com/angular/customers.php')
.map(res => res.json())
}
postJson(){
}
我想从输入接收数据并返回json字符串,然后在按下Submit时将该json字符串发布到服务。我该怎么办?
感谢阅读!
答案 0 :(得分:1)
要从输入接收数据,您可以利用控件的valueChanges属性,并在其关联的回调中使用JSON.stringify()
构建JSON字符串:
@Component({
(...)
template: `
<input [ngFormControl]="ctrl"/>
{{jsonString}}
`
})
export class SomeComponent {
constructor() {
this.ctrl = new Control();
this.ctrl.valueChanges.subscribe((value) => {
// receive the value
// build the string string from the value
// leveraging JSON.stringify()
this.jsonString = (...)
});
}
}