SAHBANI Med
SAHBANI Med

Reputation: 77

Load data before rendering component in Angular 7

I tried to recuperate data from service before rendering my component but i have this error: TypeError: Cannot read property 'dataEntries' of undefined

this is my code:

ngOnInit() {
 this.route.params.subscribe((params:Params)=>{
  this.ActivityId=params['id']
 })
 this.activityInstanceIdentifier= {
  "class":"eu.w4.engine.client.bpmn.w4.runtime.ActivityInstanceIdentifier",
  "id":this.ActivityId
 }
 this.activityInstanceAttachement= {
  "class":"eu.w4.engine.client.bpmn.w4.runtime.ActivityInstanceAttachment",
  "dataEntriesAttached":true
 }
this.activityService.getActivityInstance(this.sessionService.getPrincipal(),
                                         this.activityInstanceIdentifier,
                                         this.activityInstanceAttachement)
                                        .subscribe((ActivityInstance)=>{
                                          this.dataInstance=ActivityInstance                                 
                                        });
 }

forms = [
 {
  dataEditionMode:DataEditionMode.DISPLAY,
  name:"demande",
  editedInstance:this.dataInstance["dataEntries"]["demande"]["value"],
  component:DemandeFormComponent,
  multiple:false
 }
]

I tried to use 'resolve' also but it doesn't work , any help ?

Upvotes: 0

Views: 3130

Answers (1)

programoholic
programoholic

Reputation: 5194

JS is Asynchronous. Which means it won't wait for any I/O request to get complete and will keep executing next lines of code.

In you case getActivityInstance method is asynchronous hence JS won't wait for it to get complete and it will execute the next line . Hence

editedInstance : this.dataInstance["dataEntries"]["demande"]["value"] gets executed before service returns the data (that time dataInstance will be undefined if you haven't initialized it) .

Modify your code like this :

this.activityService.getActivityInstance(this.sessionService.getPrincipal(),
                                         this.activityInstanceIdentifier,
                                         this.activityInstanceAttachement)
                                        .subscribe((ActivityInstance)=>{
                                          this.dataInstance=ActivityInstance;

 forms = [
 {
  dataEditionMode:DataEditionMode.DISPLAY,
  name:"demande",
  editedInstance:this.dataInstance["dataEntries"]["demande"]["value"],
  component:DemandeFormComponent,
  multiple:false
 }
]
  });

Upvotes: 1

Related Questions