使用Angular2在NgZone中执行http请求

时间:2017-01-16 19:02:27

标签: angular zone zonejs

我想知道如何在Angular2区域内更新配置文件视图时执行http请求。在我的顶级个人资料组件中,我目前正在使用authHttp执行一个简单的http请求:

export class ProfileComponent implements OnInit {
    constructor(
        private auth: Auth,
        private authHttp: AuthHttp) {}

    ngOnInit() {
        // update profile information
        let headers: any = {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        };

        this.authHttp
            .get('https://' + myConfig.domain + '/api/v2/users/' + this.auth.userProfile.user_id, {headers: headers})
            .map(response => response.json())
            .subscribe(
                response => {
                    this.auth.userProfile = response;
                    localStorage.setItem('profile', JSON.stringify(response));
                },
                error => console.log(error.json().message)
            );

    }
}

问题是,由于此请求是异步的,因此配置文件页面会在 之前加载并更新配置文件。发生的事情是我第一次点击刷新没有任何反应,因为旧数据被加载到配置文件和新数据AFTER。然后我第二次点击刷新一切正常,因为它只使用从上一个请求加载的新数据。

此问题是否可以使用NgZone解决?我可以以某种方式将此请求包含在区域中,以便在完成时重新评估组件树吗?

1 个答案:

答案 0 :(得分:1)

从您的评论中我不认为它与Zones有任何关系。当@Input属性发生变化时,您需要更新辅助组件。

export class SecondaryComponent {

    private _myProperty: any;
    @Input()
    set myProperty(val: any) {
        this._myProperty = val;
        this.update();
    }

    update() { //instead of ngOnInit just use this
        //do stuff with _myProperty now
    }

}

但是,为什么不能只绑定到辅助组件中的auth.userProfile字段?除非你在辅助组件ngOnInit方法中以某种方式转换数据,否则这可能会更容易。