简体   繁体   English

Ember Octane 如何访问组件中的 Model 数据

[英]Ember Octane How to access Model data in Component

I am upgrading from Ember Classic to Ember Octane 3.17.0.我正在从 Ember Classic 升级到 Ember Octane 3.17.0。

Question:问题:

How do I access model data in a component?如何访问组件中的 model 数据?

Context:语境:

I am attempting to allow for reset password functionality.我正在尝试允许重置密码功能。 This sends a URL string to the user's e-mail.这会将 URL 字符串发送到用户的电子邮件。 When they click on the link, I am able to query the string and load the userId and token into the model.当他们点击链接时,我可以查询字符串并将 userId 和令牌加载到 model 中。 However, I cannot access that model data in the component.但是,我无法访问组件中的 model 数据。 In Classic, I achieved this with the didReceiveAttrs method, which is now deprecated.在 Classic 中,我使用didReceiveAttrs方法实现了这一点,该方法现已弃用。 The documentation suggests using getters, but I am not clear on how that is done.文档建议使用 getter,但我不清楚这是如何完成的。

See the code below.请参阅下面的代码。

Note: I have not placed this in Ember Twiddle because I do not know how;注意:我没有把它放在 Ember Twiddle 中,因为我不知道怎么做; that is another learning curve;这是另一个学习曲线; and I tried looking for a walk-through but could not find one.我试图寻找一个演练,但找不到。 If anyone wants to load this into Ember Twiddle then they have the code necessary to do so.如果有人想将它加载到 Ember Twiddle 中,那么他们有必要的代码来执行此操作。

Template Component HBS:模板组件 HBS:

<div class="middle-box text-center loginscreen animated fadeInDown">
    <div>
        <h3>Reset Password</h3>
        <form class="m-t" role="form" {{on "submit" this.resetPassword}}>
            {{#each @errors as |error|}}
                <div class="error-alert">{{error.detail}}</div>
            {{/each}}
            <Input @type="hidden" @value={{@resetPasswordModel.userId}} />
            <Input @type="hidden" @value={{@resetPasswordModel.token}} />
            <div class="form-group">
                <Input @type="password" class="form-control" placeholder="New Password" @value={{this.newPassword}} required="true" />
            </div>
            <div class="form-group">
                <Input @type="password" class="form-control" placeholder="Confirm Password" @value={{this.confirmPassword}} required="true" />
            </div>
            <div>
                <button type="submit" class="btn btn-primary block full-width m-b">Reset Password</button>
            </div>
        </form>
    </div>
</div>

Template HBS:模板哈佛商学院:

<Clients::ResetPasswordForm @resetPasswordModel={{this.model}} @resetPassword={{action 'resetPassword'}} @errors={{this.errors}} />

Route:路线:

import Route from '@ember/routing/route';
import AbcUnAuthenticatedRouteMixin from '../../mixins/abc-unauthenticated-route-mixin';

export default class ResetPasswordRoute extends Route.extend(AbcUnAuthenticatedRouteMixin) {

    model(params) {

        return {
            userId: params.strUserId,   // The strUserId found in the query parameters of the reset password URL.
            newPassword: '',
            confirmPassowrd: '',
            token: params.strToken,     // The strToken found in the query parameters of the reset password URL.
        };
    }
}

Component JS:组件 JS:

import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { action } from '@ember/object';

export default class ResetPasswordForm extends Component {

    @tracked userId;
    @tracked newPassword;
    @tracked confirmPassword;
    @tracked token;

    @action
    resetPassword(ev) {

        ev.preventDefault();

        this.args.resetPassword({
            userId: this.userId,
            newPassword: this.newPassword,
            confirmPassword: this.confirmPassword,
            token: this.token
        });
    }
}

Controller JS: Controller JS:

import Controller from '@ember/controller';
import { inject as service } from '@ember/service';
import { action } from '@ember/object';

export default class ResetPassword extends Controller {

    @service ajax;

    queryParams = ['strUserId', 'strToken'];
    strUserId = null;
    strToken = null;

    @action
    resetPassword(attrs) {

    if(attrs.newPassword == undefined || attrs.newPassword == null || attrs.newPassword == '' ||
        attrs.confirmPassword == undefined || attrs.confirmPassword == null || attrs.confirmPassword == '' ||
        attrs.newPassword != attrs.confirmPassword) 
        {

            this.set('errors', [{
                detail: "The new password and confirm password must be the same and their values and cannot be blank.  Reset password was not successful.",
                status: 1005,
                title: 'Reset Password Failed'
            }]);

            this.set('model', attrs);
        }
        else {

            this.ajax.request(this.store.adapterFor('application').get('host') + "/clients/reset-password", {
                method: 'POST',
                data: JSON.stringify({ 
                    data: {
                        attributes: {
                            "userid" : attrs.userId,
                            "new-password" : attrs.newPassword,
                            "confirm-password" : attrs.confirmPassword,
                            "token" : attrs.token
                        },
                        type: 'reset-passwords'
                    }
                }),
                headers: {
                    'Content-Type': 'application/vnd.api+json',
                    'Accept': 'application/vnd.api+json'
                }
            })
            .then(() => {

                // Transistion to the reset-password-success route.
                this.transitionToRoute('clients.reset-password-success');
            })
            .catch((ex) => {

                this.set('errors', ex.payload.errors); 
            });
        }
    }
}

you can get the model data in the component by initializing you attribute using this.args您可以通过使用 this.args 初始化属性来获取组件中的 model 数据

@tracked userId = this.args.resetPasswordModel.userId;

and in the component template并在组件模板中

<Input @type="hidden" @value={{this.userId}} />

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

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