-1

I want to retrieve a list of objects "listOfArticles" from the back before to call next methods which initialize form and use validators on this list. But in my case, the form is initialized before the end of http request (because of asynchronous method). How to fix it ?

Method of managementArbo.service.ts :

constructor(private http: Http) { }

  getProducts(parametres :string) :Observable<any> {
    console.log("Dans getProducts avec "+parametres);
    let url :string = "http://#####"+parametres;
    let observable :Observable<any> = this.http.get(url).map((res:Response) => res.json());
    return observable;
 }

ngOnInit() method of myForm.ts

ngOnInit() {
    this.getListBdd();
    this.myFormGroup = this.fb.group({
      itemRows: this.fb.array([this.initItemRows()])
    })
}

getListBdd() method of myForm.ts

public getListBdd() {
    this.route.params.subscribe((params: Params) => {
      let subroute = "getRefNumber";
      this.managementArbo.getProducts(subroute)
        .subscribe(
          res => { this.listOfArticles = res; console.log('bdd:' + res); }

          ,
          err => console.log(err),
          () => console.log('getProducts done'));
    });
}
3
  • 1
    Move that logic into the subscribe callback Commented Jul 23, 2018 at 14:48
  • 1
    Possible duplicate of wait for Http response in angular 2 Commented Jul 23, 2018 at 14:50
  • @user184994 Can you develop it a little more? Commented Jul 23, 2018 at 14:58

1 Answer 1

1

Move all your form initialization code inside subscribe of getListBdd()

public getListBdd() {
    this.route.params.subscribe((params: Params) => {
      let subroute = "getRefNumber";
      this.managementArbo.getProducts(subroute)
        .subscribe(
          res => { 
           this.listOfArticles = res; console.log('bdd:' + res); 

           // create your form here;
           this.myFormGroup = this.fb.group({
                    itemRows: this.fb.array([this.initItemRows()])
            })
         },
          err => console.log(err),
          () => console.log('getProducts done'));
    });
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.