简体   繁体   中英

How to assign JSON object parameters to some values in typescript?

I am currently using angular 2.0. I have a json object returned by a method like this.

this.propertiesService.addSeriesToChart(this.testId).subscribe(result => {
        this.result = result;
        });

The addSeriesToChart() is in service which returns json object.

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. 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. You can use an output property to emit the data that you receive on subscribing.

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:

export class Data{
   id:number;
   name:string;
}

Now in order to use the above AppComponent elsewhere in your app, you can bind the event:

<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. Try with it.

首先,您可以在发送响应时在服务时使用result.JSON()将对象转换为JSON,然后当您收集该JSON对象时,您必须将其转换为this.result = JSON.stringify(result)它适用于mi

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM