d123546
d123546

Reputation: 247

angular 2 *ngFor and Observables Object, no data displayed

I've checked a certain questions already, but still didn't manage to solve my issue. I'm using a service in my app which returns observables, everything is fine on this stage, but when I want to display the data, nothing happens:

@Injectable()
export class DataService {

    private APIURL = 'http://api.dev/'; 

    constructor(private http: Http) {
    }

    _API_getEvents:string = this.APIURL + "getEvents";
    getEvents() : Observable<IEvent[]> {
        return this.http.get(this._API_getEvents)
        .map((res:Response) => res.json())
        .catch(this.handleError);
    }

    private handleError (error: Response | any) {
        // In a real world app, we might use a remote logging infrastructure
        let errMsg: string;
        if (error instanceof Response) {
          const body = error.json() || '';
          const err = body.error || JSON.stringify(body);
          errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
        } else {
          errMsg = error.message ? error.message : error.toString();
        }
        console.error(errMsg);
        return Observable.throw(errMsg);
    }


}

Event Interface:

export interface IEvent {
    id: number;
    name: string;
    created_at:Date;
    update_at:Date;
}

And component:

events:IEvent[];
//events:any[];

  constructor(private _http:Http, private _dataService: DataService)
  {
    this._dataService.getEvents()
    .subscribe(

      function(response) { console.log("Success Response" + response); 

        this.events = response;
        console.log('EVENTS: ');
        console.log(this.events);
      },
      function(error) { console.log("Error happened" + error)},
      function() { console.log("the subscription is completed")}
    );
  }

When I'm trying to display, its empty:

 <ul *ngIf="events">
                    <li *ngFor="let event of events">
                        <a [routerLink]="['/gallery/', 'event1']">
                            {{event.name}}
                        </a>
                    </li>
...

What could be the issue?

Upvotes: 0

Views: 451

Answers (1)

JB Nizet
JB Nizet

Reputation: 691953

Use arrow functions. Without them, this is not bound to the component instance in your calback functions:

.subscribe(response => { 
    console.log("Success Response" + response); 
    this.events = response;
}, 
...

Upvotes: 1

Related Questions