【问题标题】:Execute http request inside NgZone with Angular2使用 Angular2 在 NgZone 中执行 http 请求
【发布时间】:2017-01-17 03:28:15
【问题描述】:

我想知道如何在 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)
            );

    }
}

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

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

【问题讨论】:

  • 对此我还是有点困惑。什么不更新?你的看法?您是否绑定到视图中的 auth.userProfile?当通过 authHttp 的请求返回时它没有更新?
  • @Steveadoo 我正在将来自auth.userProfile 的一些数据作为输入传递到配置文件组件模板中的另一个组件中,因此它在auth.userProfile 可以之前将旧数据作为输入传递由http请求更新
  • 你怎么知道这是区域问题?查看 AuthHttp,它看起来不像在 angular 区域之外运行。如果您将 auth.userProfile 作为 @Input() 属性传递给您的其他组件,那么当您更改它时它应该会自动更新。您是否碰巧在其他组件的 ngOnInit 中读取 @Input 属性?
  • @Steveadoo 我确实在阅读和使用其他组件 NgOnInit 中的 @input 属性,这会是问题的根本原因吗?
  • 是的,先生,试着让他们成为二传手,然后在上面调用某种更新方法。我会发布一个更详细的答案。

标签: angular zone zonejs


【解决方案1】:

从您的 cmets 来看,我认为这与 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 方法中以某种方式转换数据,否则这可能会更容易。

【讨论】:

    猜你喜欢
    • 2015-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-25
    • 1970-01-01
    • 2016-11-27
    • 2017-03-24
    相关资源
    最近更新 更多