Angular 2: Populate checkbox list with HTTP response

I am using Angular 2 for my web application. Now I am trying to populate a checkbox list from backend service call. This is what I am trying.

main.ts

import {bootstrap}        from 'angular2/platform/browser';
import {ROUTER_PROVIDERS} from 'angular2/router';
import {HTTP_PROVIDERS} from 'angular2/http';
import 'rxjs/add/operator/map';

import {DataService} from './service'
import {AppComponent}     from './app.component';

bootstrap(AppComponent, [ROUTER_PROVIDERS,HTTP_PROVIDERS,DataService]);

service.ts

import {Http, Response} from 'angular2/http'
import {Injectable} from 'angular2/core'

@Injectable()
export class DataService {

  http: Http;
  constructor(http: Http) {
    this.http = http;
  }

  getCheckboxList() {
    return this.http.get('http://localhost:8080/test/getList').map((res: Response) => res.json());
  }

}

checkbox.ts

import {Component} from 'angular2/core';
import {DataService} from '../service';

@Component({
  templateUrl: 'views/checkboxlist.html'
})

export class CheckboxComponent {
  message = "hello";
  constructor(dataService: DataService) {
    dataService.getCheckboxList().subscribe(function(res) {
        console.log(res.result);
        this.list = res.result;
        console.log(this.list);

    })
  }
}

checkboxlist.html

<div>
  <label *ngFor="#item of list">
    <input type="checkbox">{{item.value}}
  </label>
</div>

Backend service is successful and returns a response and line console.log(this.list); prints an object array (HTTP response). Although, it doesn’t display the checkbox list and there is not any error on the console log.

Does anyone have any idea what’s wrong with my code?

Thank You

2
Leave a Reply

avatar
2 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Jason
Guest

I would expect an error message in the browser console

Try the safe-navigation ?.

<input type="checkbox">{{item?.value}}

Jason
Guest

You should use an arrow function in your component to be able to use the lexical this. In this case, the this keyword will correspond to the instance of the component. In your case, you use a “normal” function and the this keyword used in it doesn’t correspond to the component instance…

dataService.getCheckboxList().subscribe((res) => { // <--------
    console.log(res.result);
    this.list = res.result;
    console.log(this.list);

})

See this plunkr: https://plnkr.co/edit/r1kQXlBVYvuO5fvQJgcb?p=preview.

See this link for more details: