Как исправить этот Кодекс, чтобы получить данные от сервиса и отправить их в мою форму с помощью Реактивной формы? - PullRequest
0 голосов
/ 02 мая 2019

В моем приложении я создаю поддельный сервер, чтобы получать от него значения, и использую сервис, чтобы вернуть все значения и отправить его в мою форму.

1.Мой HTML:

    <form [formGroup]="Field"> 
  <table class="table">
        <tr>
            <th scope="col">Branch</th>
            <th scope="col">Realisation N-1</th>
            <th scope="col">L'objectifs</th>
            <th scope="col">Taux de Croissance</th>
        </tr>
        <tr  class="back-color">
            <td><label formControlName="nom" ></label></td>
            <td><input formControlName="realisation"   /></td>
            <td><input formControlName="objectif"      /></td>
            <td><input formControlName="TC"            /></td>
        </tr>
        <tr FormArrayName="sousbranch"> 
            <td><label formControlName="s_nom"></label></td>
            <td><input formControlName="s_realisation"  /></td>
            <td><input formControlName="s_objectif"       /></td>
            <td><input formControlName="s_TC"           /></td>
        </tr>
  </table>
</form>

2.my ОБСЛУЖИВАНИЕ:

   baseUrl = http://localhost:3000/branche       

   constructor(private httpClient: HttpClient) {}      

// ... получить всю ветку с сервера

     getBranches(): Observable<Ibranch[]>{        
       return this.httpClient.get<Ibranch[]>(this.baseUrl)      
            .pipe(catchError(this.handleError));        
        }   

3.my Метод компонента:

//.. Ibranch - это интерфейс, у которого все имя ключа ветви
(.. Ibranch имеет массив IsBranch)
// .. IsBranch - это также интерфейс, имеющий все значения souBranch

branches : Ibranch[]; 
  constructor(private fb: FormBuilder,
              private _BranchesService:BranchesService) {
}
 Field : FormGroup;
  ngOnInit() {
    this.Field = this.fb.group({
      nom : [''],
      objectif : [''],
      realisation : [''],
      TC : [],
      sousbranch : this.fb.array([
          this.fb.group({
            s_nom : [],
            s_realisation : [],
            s_objectif : [],
            s_TC : []
          })
      ])
    });
  } 


// .. подписаться на метод getBranches:

 getBranche(){
    this._BranchesService.getBranches().subscribe( 
      (branch : Ibranch[]) => this.setBranch(branch['']),
      //(branch : Ibranch[]) => branch[''],
      (err : any)      => console.log(err)
    );
  } 

                   <br>

// .. установить значения в форме

setBranch(branche : Ibranch){
     this.Field.patchValue({
          nom : branche.nom,
          realisation : branche.Taux_de_Croissance,
          objectif : branche.objectif,
          TC : branche.Taux_de_Croissance,
     });  this.Field.setControl('sousbranch',this.setExistingSBranch(branche.sousBranch))
  }
  setExistingSBranch(branchset : Isbranch[]) : FormArray{
   const Formarray = new FormArray([]);
  branchset.forEach(b => {
    Formarray.push(this.fb.group({
       s_id : b.s_id,
       s_nom : b.s_nom,
       s_realisation : b.s_realisation,
       s_objectif : b.s_objectif,
       s_Taux_de_Croissance : b.s_Taux_de_Croissance  
     }))
   });
   return Formarray;
  }   


обратите внимание, что каждая ветвь имеет несколько дочерних ветвей, и это изображение объяснит результат, который я ищу для этого это результат:

код в stackblitz: https://stackblitz.com/edit/angular-cdzfrw
но приложение не работает.

большое спасибо за ответ на мой вопрос

...