简体   繁体   中英

Angular 2: Template not updating after http service update

I'm still trying to learn ng2 so I'm sure this is a common noob problem but none of the solutions I found online helped. anyone know what my problem is?

I have a service with the getEventList() method as an observable

getEventList(): Observable<any>{
    return this.http.get('./assets/data.json')
        .map(response => response.json());
}

I subscribe to it in my component

ngOnInit(){
    this.eventService.getEventList()
        .subscribe(events => {
            this.zone.run(()=>{
                this.events = events;
                console.log(this.events)
            });
        });
}

My template just tries to output the events variable in json format

<p>
    {{
        events | json
    }}
</p>

As you can see I'm assigning the value of events to a local variable in a zone.run() callback. Still not seeing my template update. I've also tried ApplicationRef.tick and ChangeDetectorRef.detectChanges() but neither seem to detect my changes.

Console.log call does confirm that the data was updated. Any click handler fired on this component also seems to update the view.

Anyone know what I'm doing wrong here? Did I post enough of the code to get some advice? Let me know what else you would like to see.

This should do it, assuming you haven't assigned a value to this.events before calling getEventList() method:

<div *ngIf="events">
{{ events | json }}
</div>

The seed was setting the ChangeDetectionStrategy to OnPush. Setting this to default solved my problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM