Angular 6:无法从不同组件的JSON对象获取单个数据

时间:2019-11-16 01:35:09

标签: json angular

场景: 在Component1中,我有一张表,我正在将单行数据作为JSON对象发送到Component2的对象

预期结果: 我应该能够使用object2来获取数据,例如。 object2.id = id1object2.title = title1

实际结果:我对object2 object2.id= undefinedobject2.title = undefined

中的值不确定

我尝试过的事情: 在Component1中,我使用了JSON.stringify(obj);在Component2中,我使用了JSON.parse(obj)来获取对象值,但是在警告JSON对象时,我却得到了[obj obj]。 我对不使用任何JSON.parse的JSON如何自动将其转换为Obj感到困惑。

好消息是,数据正在传递给object2,当我警告object2时,我得到了带有所有值的整个对象字符串。 但是当我尝试填充单个值时,尽管存在值,但仍给了我未定义的味精

有什么想法我还能检查为什么它不起作用吗?

不确定我到底缺少什么,过去几天以来我一直在搜索,在此站点或任何其他站点上都找不到任何解决方案。 任何帮助表示赞赏。谢谢。

这是我的代码: Component1

@Component({
  selector: 'myjds',
  templateUrl: './myjds.component.html',
  styleUrls: ['./myjds.component.scss'],
  providers: [DatePipe]
})

@NgModule({
  imports: [
    ThemeModule,
    NgxEchartsModule, Ng2SmartTableModule,
    NgxChartsModule, ChartModule, NgxSpinnerModule
  ],
  declarations: [
    DashboardComponent,
    StatusCardComponent,
    ContactsComponent,
    EchartsPieComponent,
    EchartsBarComponent,
  ],
  entryComponents: []

})

export class MyjdsComponent implements OnInit {

  config: ToasterConfig;
  private message = null;

  position = 'toast-top-right';
  animationType = 'flyLeft';
  title = 'Result';
  content = `I'm cool toaster!`;
  timeout = 5000;
  toastsLimit = 5;
  type = 'info';

  isNewestOnTop = true;
  isHideOnClick = true;
  isDuplicatesPrevented = false;
  isCloseButton = true;
  EntityID;
  LoginUserId;

  jdData: JobDescription[] = [];
  indJobDescription = {} as JobDescription;
  source: LocalDataSource = new LocalDataSource();
  serachResults = [];
  public nijobmobile;
  public nijobcontactemail;

  constructor(
    private ServiceObj: ApiService, 
    private spinner: NgxSpinnerService, 
    private modalService: NgbModal, 
    private toasterService: ToasterService, 
    private activeModal: NgbActiveModal,
    private datePipe: DatePipe) {
    this.EntityID = localStorage.getItem("Entity");
    this.LoginUserId = localStorage.getItem("LoginID");
  }
  private showToast(type: string, title: string, body: string) {
    this.config = new ToasterConfig({
      positionClass: this.position,
      timeout: this.timeout,
      newestOnTop: this.isNewestOnTop,
      tapToDismiss: this.isHideOnClick,
      preventDuplicates: this.isDuplicatesPrevented,
      animation: this.animationType,
      limit: this.toastsLimit,
    });
    const toast: Toast = {
      type: type,
      title: title,
      body: body,
      timeout: this.timeout,
      showCloseButton: this.isCloseButton,
      bodyOutputType: BodyOutputType.TrustedHtml,
    };
    this.toasterService.popAsync(toast);
  }
  ngOnInit() {   
    this.loadJobDescription();
  }
  loadJobDescription(jdData?) {  
    if (jdData == null || jdData == undefined || jdData == 0) {
      alert("data null e ");
      this.spinner.show();
      let body = JSON.stringify({
        nispname: "nijobdescriptionsearch_sp",
        ptype: "alljobdescription",
        pnijobdescriptionid: 0,
        pniuserid: Number(this.LoginUserId),
        pnicompid: this.EntityID
      });
      alert("body string value : " + body);
      this.ServiceObj.apicall(body).subscribe(
        res => {
          this.spinner.hide();
          let data: any = res;
          if (data.results.Table.length > 0) {
            alert("table returns values:" + data.results.Table.length);
            this.jdData = data.results.Table;            
            localStorage.setItem('Message', JSON.stringify(this.jdData));
            this.source.load(this.jdData);            
          }
        },
        (err) => {
          this.spinner.hide();
        }
      );
    }
    else {
      alert("data ahe baba");
      let loginUserId = localStorage.getItem("LoginID");
      alert("loginUserId: " + loginUserId);
      this.spinner.show();
      let body = JSON.stringify({
        nispname: "nijobdescriptionsearch_sp",
        ptype: "individualJD",
        pnijobdescriptionid: jdData.nijobdescriptionid,
        pniuserid: Number(this.LoginUserId),
        pnicompid: this.EntityID
      });
      alert("body stringify:" + body);
      this.ServiceObj.apicall(body).subscribe(
        res => {
          this.spinner.hide();
          let data: any = res;
          if (data.results.Table.length > 0) {
            alert("data length" + data.results.Table.length);
            this.indJobDescription = data.results.Table;
            localStorage.setItem('Message1', JSON.stringify(this.indJobDescription));
            // alert("result of indjobdescription: " + JSON.stringify(this.indJobDescription));
            const activeModal = this.modalService.open(IndJobDescriptionComponent, {
              size: 'lg',
              backdrop: 'static',
              container: 'nb-layout',
            });
          }
        },
        (err) => {
          this.spinner.hide();
        }
      );
    }
  }
}

Component2

  selector: 'commentresult',
  templateUrl: './indjobdescription.component.html',
  styleUrls: ['./indjobdescription.component.scss']
})
export class IndJobDescriptionComponent implements OnInit {

  private msg: string = '';
  private msg1: string = "";
  public dialog: any;
  public dialog1 :any;
  public existingstaffid = [];
  errorMsgRolename: string = '';
  errorMsgRoledescription: string = '';
  isValidRolename: boolean = true;
  isValidRoledescription: boolean = true;
  public ShlocationAutoComplete;
  public ShroleAutoComplete;
  public ShskillAutoComplete;
  public ShdomainAutoComplete;
  public ShcertAutocomplete;
  public alldata;
  public nijobmobile;
  public nijobcontactemail;


  pager: any = {};
  pagedItems: any[];

  jdData: JobDescription[] = [];  
  indJobDescription = {} as JobDescription;

  LoginUserId = localStorage.getItem("LoginID");
  source: LocalDataSource = new LocalDataSource();

  constructor(private modalService: NgbModal,
    private spinner: NgxSpinnerService,
    private _sanitizer: DomSanitizer,
    private data: DataService,
    private activeModal: NgbActiveModal,
    private ServiceObj: ApiService, 
    private pagerService: PagerService,
    private toasterService: ToasterService) {
    this.EntityID = localStorage.getItem("Entity");

  }
  profile: any;
  private EntityID: string;
  private message = null;
  config: ToasterConfig;
  position = 'toast-top-right';
  animationType = 'flyLeft';
  title = 'Result';
  content = `I'm cool toaster!`;
  timeout = 5000;
  toastsLimit = 5;
  type = 'info';
  isNewestOnTop = true;
  isHideOnClick = true;
  isDuplicatesPrevented = false;
  isCloseButton = true;


  ngOnInit() {
    this.msg1 = localStorage.getItem("Message1");   
    //this.indJobDescription = JSON.parse(this.msg1);  //on doing alert, this line is returning [obj obj]   
    alert("user id: " + this.indJobDescription.nijobcreateuserid);

  }

  closeModal() {
    this.activeModal.close();
  }

  private showToast(type: string, title: string, body: string) {
    this.config = new ToasterConfig({
      positionClass: this.position,
      timeout: this.timeout,
      newestOnTop: this.isNewestOnTop,
      tapToDismiss: this.isHideOnClick,
      preventDuplicates: this.isDuplicatesPrevented,
      animation: this.animationType,
      limit: this.toastsLimit,
    });
    const toast: Toast = {
      type: type,
      title: title,
      body: body,
      timeout: this.timeout,
      showCloseButton: this.isCloseButton,
      bodyOutputType: BodyOutputType.TrustedHtml,
    };
    this.toasterService.popAsync(toast);
  }

  SaveData() {
    let t = window.location.host;
    let tvpselectiondtl: tvp_selectiondtl[] = [];
    let LoginUserId = localStorage.getItem("LoginID");
  }
}

JSON字符串的PFB屏幕截图,很抱歉console.log无法正常工作,因此必须对警报进行屏幕截图

enter image description here

2 个答案:

答案 0 :(得分:0)

有两种在组件之间共享数据的主要方法,即输入和输出属性以及共享服务。

如果组件2是组件1的子代,则使用输入

<component2 [data]="propertyOfComponent1"></component2>

在组件2中,将data属性装饰为输入

@Input() data;

在初始化组件后,数据将是从组件1传递的数据。您可以使用ngOnInit方法访问它,但不能访问构造函数,因为它尚未被连接。

如果它们不在父子关系中,则使用共享注入到两个组件构造函数中的依赖项的共享服务。

constructor(private sharedService: SharedService) {
}

,两个组件都将获得相同的服务实例。

@Injectable()
export class SharedService {
  data = new SomeObject();
}

答案 1 :(得分:0)

正如我在json中看到的那样,您正在存储对象数组。

this.msg1 = localStorage.getItem("Message1");   
this.indJobDescription = JSON.parse(this.msg1);  //on doing alert, this line is 
     returning [obj obj]   
alert("user id: " + this.indJobDescription[0].nijobcreateuserid);   //It is array

如果有多个indJobDescription条目,则使用* ngFor读取每个对象。

  for (let i = 0; i < this.indJobDescription.length ; i++) {
      var jobCreateUserId= this.indJobDescription[i].nijobcreateuserid;
      ..........
  }

它将解决您的问题。

保持简单

 var product=[{"sno":"1","description":"test"}] =Array of object ==>product[0].sno
 var product={"sno":"1","description":"test"} = it presents object.  ==> product.sno