[英]How to assign JSON object parameters to some values in typescript?
I am currently using angular 2.0. 我目前正在使用angular 2.0。 I have a json object returned by a method like this.
我有一个像这样的方法返回的json对象。
this.propertiesService.addSeriesToChart(this.testId).subscribe(result => {
this.result = result;
});
The addSeriesToChart() is in service which returns json object. addSeriesToChart()正在使用中,它返回json对象。
In the result returned, I have to assign some of the null values to few default values, I am trying like 在返回的结果中,我必须将一些空值分配给一些默认值,我正在尝试像
if (this.result != undefined && this.result != null) {
this.result.json().channel.mark = "ABC"
But the mark parameter inside the json object does not seem setting "ABC", it always remain null. 但是json对象内部的mark参数似乎未设置为“ ABC”,它始终保持为null。 Am I doing something wrong here?
我在这里做错什么了吗?
Say you have a variable data
in component class that you want to assign the data coming from json. 假设您要分配来自json的
data
在组件类中有一个可变data
。 You can use an output
property to emit the data that you receive on subscribing. 您可以使用
output
属性来发出您在订阅时收到的数据。
You can do this: 你可以这样做:
import { Component, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'user',
template: '<div>Hi</div>'
})
export class AppComponent{
data:Data;
@Output() dataOutput:EventEmitter<Data> =
new EventEmitter<Data>()
this.propertiesService.addSeriesToChart(this.testId).subscribe(result => {
this.data = result.json();
this.dataOutput.emit(this.data);
});
}
Here Data
will be your model containing variables that you can map the json to: 这里的
Data
将是您的模型,其中包含可以将json映射到的变量:
export class Data{
id:number;
name:string;
}
Now in order to use the above AppComponent
elsewhere in your app, you can bind the event: 现在,为了在应用程序的其他位置使用上述
AppComponent
,可以绑定事件:
<user (dataOutput)="receiveData($event)"></user>
export class PageComponent {
datareceived:Data;
constructor(){}
receiveData(data){
this.datareceived=data;
}
getUIData(value: any) {
for (var name in value.selected) {
if (this.datareceived!= undefined && this.datareceived!= null) {
if (name == 'mark')
//do whatever you feel like
}
}
}
}
I think this will solve the case pretty much. 我认为这将解决很多情况。 I know this isn't exactly the solution as per your json but its a simplified way to get to it.
我知道这并不是您的json所提供的解决方案,而是一种简化的解决方案。 Try with it.
试试吧。
首先,您可以在发送响应时在服务时使用result.JSON()将对象转换为JSON,然后当您收集该JSON对象时,您必须将其转换为this.result = JSON.stringify(result)它适用于mi
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.