GET请求后属性未在DOM上更改

时间:2019-04-11 13:11:28

标签: polymer-1.0

我正在研究一个组件以呈现用户详细信息。从API请求中获取详细信息,并更新了属性,但这些更改未反映在DOM上。

我工作的公司仍在使用Polymer 1.2,我很难找到和理解文档。我是否需要从父组件发出get请求,或者可以直接在组件内部进行获取请求?我有些根本不了解的东西,想知道是否有人可以为我提供一些启发。

谢谢。

模板中的代码段

<p>{{i18n.GLOBAL_USERNAME}} - [[username]]</p>
<p>{{i18n.GLOBAL_FIRSTNAME}} - [[firstname]]</p>
<p>{{i18n.GLOBAL_LASTNAME}} - [[lastname]]</p>
<p>{{i18n.GLOBAL_EMAIL}} - [[email]]</p>
<p>{{i18n.GLOBAL_NUMBER}} - [[number]]</p>

聚合物功能的摘录:

Polymer({
            is: 'my-component',

            properties: {
                username: { 
                    type: String, 
                    value: "n/a",
                },
                firstname: { 
                    type: String, 
                    value: "n/a"
                },
                lastname: { 
                    type: String, 
                    value: "n/a"
                },
                email: { 
                    type: String, 
                    value: "n/a"
                },
                number: { 
                    type: String, 
                    value: "n/a"
                },
            },

            ready: function () {
                var user = app.auth.hasSession()
                if (user !== null) {
                    app.getUserInfo(user.user_id, this._getUserSuccessful, this._getUserFail);
                }
            },

            _getUserSuccessful: function (res) {
                this.username = res.user.user_id
                this.firstname = res.user.firstname
                this.lastname = res.user.lastname
                this.email = res.user.email
                this.number = res.user.phone_number
                console.log("got user details")
            },
            _getUserFail: function () {
                console.log("failed to get user details")
            },
        });

1 个答案:

答案 0 :(得分:0)

您需要使用Polymer setter methods而不是普通分配。

这是一个例子:

_getUserSuccessful: function (res) {
  this.set('username', res.user.user_id)
  this.set('firstname', res.user.firstname)
  this.set('lastname', res.user.lastname)
  this.set('email', res.user.email)
  this.set('number', res.user.number)
  console.log("got user details")
},

对于数据绑定属性,需要使用setter和/或array mutator方法,否则Polymer不能知道已进行了某些更改以更新绑定。

我真的建议您在继续进行Polymer 1.x的任何工作之前,先阅读整篇Data system concepts文章。