简体   繁体   English

Angular 2:http服务更新后模板未更新

[英]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. 我还在努力学习ng2所以我确定这是一个常见的noob问题,但我在网上找到的解决方案都没有帮助。 anyone know what my problem is? 有谁知道我的问题是什么?

I have a service with the getEventList() method as an observable 我有一个getEventList()方法的服务作为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 我的模板只是尝试以json格式输出事件变量

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

As you can see I'm assigning the value of events to a local variable in a zone.run() callback. 正如您所看到的,我将事件的值分配给zone.run()回调中的局部变量。 Still not seeing my template update. 仍未看到我的模板更新。 I've also tried ApplicationRef.tick and ChangeDetectorRef.detectChanges() but neither seem to detect my changes. 我也尝试过ApplicationRef.tick和ChangeDetectorRef.detectChanges(),但似乎都没有检测到我的更改。

Console.log call does confirm that the data was updated. Console.log调用确认数据已更新。 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: 这应该这样做,假设您在调用getEventList()方法之前没有为this.events分配值:

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

The seed was setting the ChangeDetectionStrategy to OnPush. 种子将ChangeDetectionStrategy设置为OnPush。 Setting this to default solved my problem. 将此设置为默认值可解决我的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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