0

I have a problem. I'm newbie in Angular and I try, to load data from backend (c#) and show it on the front.

In my backend I have a List of Models fills with sample data.

public static List<CheckModel> checkModels = new List<CheckModel>();

CheckModel looks like this:

public string Id { get; set; }
public string Name { get; set; } 

And now I'm trying to view this in Angular. If i create list like this directly in my component.ts:

ordersData = [
{ id: 100, name: 'order 1' },
{ id: 200, name: 'order 2' },
{ id: 300, name: 'order 3' },
{ id: 400, name: 'order 4' }
];

Then i can view this in html table and everything is okay. To the every row in table I would like to add checkbox, so I used this method:

private addCheckboxes() {
this.ordersData.forEach(() => this.ordersFormArray.push(new FormControl(false)));
}

I would to load data from my API. I tried this way:

constructor(
    private http: HttpClient,
    private formBuilder: FormBuilder
    ) {
  this.form = this.formBuilder.group({
    orders: new FormArray([])
  });
  this.addData();
  this.addCheckboxes();
}

private addData() {
    return this.http.get<CheckModel[]>('api/check/getData')
};

ordersData: CheckModel[];
  
private addCheckboxes() {
this.ordersData.forEach(() => this.ordersFormArray.push(new FormControl(false)));
}

But this case isn't work. Developers tools in Chrome shows me an error:

core.js:6014 ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'forEach' of undefined
TypeError: Cannot read property 'forEach' of undefined

So, how can i load data from my API to the ordersData list? Please, forgive me for banal questions!

1 Answer 1

1

You need to subscribe to fetch the value when it is available.

  private addData() {
    return this.http.get<CheckModel[]>('api/check/getData').subscribe(
            (checkModelArray: CheckModel[]) => {
            this.ordersData = checkModelArray;
            this.addCheckboxes()
                         });
};

Also remove this.addCheckboxes() from constructor!!! It can not be fired by constructor since the data it needs will be undefined.

Subscription will return at a later time but constructor will run initialy when angular creates the component. The data that the constructor needs will not be available when the constructor executes. So you have to force your logic inside the subscription function.

Sign up to request clarification or add additional context in comments.

2 Comments

You're the best! Thank You very much, It's working :D
@Vidaloka please mark it as accepted if problem is solved.

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.