[英]ember helper waiting for an ajax request
我在初始化方法調用ajax請求時編寫了一個余燼組件
init(){
this._super(...arguments);
const context = this;
if ((this.get('localStorage').getItem('idProfileDesa')) !== null && (this.get('localStorage').getItem('idProfileDesa')) !== undefined) {
if ((this.get('localStorage').getItem('idProfileDesa')) !== 0) {
this.get('registerProfileDesaService').findByProfileFormId(this.get('localStorage').getItem('idProfileDesa')).then(
function (response) {
context.debug(JSON.stringify(response));
context.set("alamat", response.alamat);
context.set("kodeWilayah", response.kodeWilayah);
context.set("noTelp", response.noTelepon);
context.set("lokasiWilayah", response.lokasiWilayah);
context.set("email", response.email);
context.set("website", response.website);
context.set("jumlahDusun", response.jumlahDusun);
context.set("jumlahRw", response.jumlahRW);
context.set("jumlahRt", response.jumlahRT);
context.set("jumlahKepalaKeluarga", response.jumlahKepalaKeluarga);
context.set("jumlahRumahTangga", response.jumlahRumahTangga);
context.set("jumlahPenduduk", response.jumlahPenduduk);
context.set("lokasiKantor", response.lokasiKantor);
context.set("pos", response.pos);
}, function (e) {
context.debug(e);
context.get('commonService').showNotification(e);
});
}
}
}
這是可行的,但不幸的是我的ember幫助程序沒有等待ajax請求,並說控制台日志中的“數據”未定義
import Ember from 'ember';
export function validateIsEmail(params/*, hash*/) {
let email = params[0];
let mustHaveChar = ["@",".com",".co.id",".id",".org"];
let didHasWord = 0;
mustHaveChar.forEach(function (word) {
didHasWord = didHasWord + email.includes(word);
});
return (didHasWord > 1);
}
export default Ember.Helper.helper(validateIsEmail);
如何使我的余燼助手等待一個ajax請求?
在將數據加載到組件內部之前,請三思而后行。 組件應盡可能隔離。 我了解,在很多情況下,我們必須在組件內部加載數據。 在您的情況下,您可以通過將數據從父容器(可能是控制器)傳遞到組件,方法是將數據加載到容器內部並將其傳遞給組件以進行渲染。
為了回答您的問題,幫助程序將在模板中被調用后立即負責,並且不會擔心組件的狀態。 因此,在數據完全加載之前,請不要調用輔助程序。
在您的組件文件中,
init() {
this._super(...arguments);
this.set('isLoading', true); // <- setting the loading state explicitly
$.ajax('https://jsonplaceholder.typicode.com/users').then((data) => {
this.set('users', data);
this.set('isLoading', false); // <- make it false after the data loads
});
}
在您組件的模板中,
{{#unless isLoading}} <!-- render the component only if the data finished loading -->
{{#each users as |user|}}
<li>{{user.name}} :
{{#if (isemail user.email)}}
{{user.email}}
{{else}}
<span style="color: red">(The email is invaild)</span>
{{/if}}
</li>
{{/each}}
{{/unless}}
請參閱此方法以獲取詳細的調用: https ://ember-twiddle.com/53bd472bbeaa42d1790da2ba97a6a803?openFiles = templates.components.my-comp.hbs%2Ctemplates.components.my-comp.hbs
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.