Home > OS >  Store subscribe result and patch it
Store subscribe result and patch it

Time:10-31

How can I store the data on requestArray and then use that to patch it?

requestArray is not usable on the code

I tried but it gives me undefined one line before patching it.

  ngOnInit(): void {
    this.getOneRequest(localStorage.getItem("xyz")); //returns id of the array
  }

  requestArray: any;

  data={areaOfInterest:"",resourceDTOS:[{seniority:"",skillDTOS:[{skill:"",},],resourceNotes:"",},],}; 
//just a json

  myForm: FormGroup;

  constructor(private fb: FormBuilder, private requestService: RequestService) {
    this.myForm = this.fb.group({
      areaOfInterest: [""],
      startDate: [""],
      endDate: [""],
      description: [""],
      notes: [""],
      resourceDTOS: this.fb.array([]),
    });
    this.setResourceDTOS();

    console.log(this.requestArray); //returns undefined
    this.myForm.patchValue(this.requestArray);
  }

  getOneRequest(id: string) {
    return this.requestService.GetSingleRequest(id).subscribe((data) => {
      console.log(data);
      JSON.stringify(data);
      this.requestArray = data;
    });}

What can I do to potentially fix this?

CodePudding user response:

The constructor method always executes before ngOnInit. Also, the response is only usable within the API request.

To resolve this issue, move the API request into the constructor and call the patchValue function within the request:

New Constructor:

 constructor(private fb: FormBuilder, private requestService:      RequestService) {
     this.myForm = this.fb.group({
       areaOfInterest: [""],
       startDate: [""],
       endDate: [""],
       description: [""],
       notes: [""],
        resourceDTOS: this.fb.array([]),
      });
      this.setResourceDTOS();

   this.requestService.GetSingleRequest(id).subscribe((data)      => {
       console.log(data);
       JSON.stringify(data);
       this.requestArray = data;

      console.log(this.requestArray); //will no longer be undefined
      this.myForm.patchValue(this.requestArray);
   });
 }
  • Related