首页 > 解决方案 > Angular 6:无法从不同组件的 JSON 对象中获取单个数据

问题描述

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

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

实际结果:我在 object2 中的值未定义object2.id= undefined,,object2.title = undefined

我尝试了什么: 在 Component1 中我使用JSON.stringify(obj)和在 Component2 中我JSON.parse(obj)用来获取对象值,但我[obj obj]对 JSON 对象保持警觉。我对 JSON 如何在不使用任何 JSON.parse 的情况下自动转换为 Obj 感到困惑。

好消息是,数据正在传递给 object2,当我提醒 object2 时,我得到了包含所有值的整个对象字符串。但是当我尝试填充单个值时,尽管存在值,但它给了我未定义的 msg

知道我还能如何检查它为什么不工作吗?

不知道我到底错过了什么,我从过去几天开始搜索,在这个或任何其他网站上没有找到任何解决方案。 任何帮助表示赞赏。谢谢。

这是我的代码: 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();
        }
      );
    }
  }
}

组件2

  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 无法正常工作,因此不得不截取警报的屏幕截图,

在此处输入图像描述

标签: jsonangular

解决方案


正如我在 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

推荐阅读