angular - 在 Angular 中加载 DOM 之前在服务中运行函数
问题描述
我有一个 Angular 网站,我在其中使用品牌代码动态加载品牌并控制网站上的其余功能。如果用户在加载该品牌之前点击了网站上的任何内容(即,如果与 API 的连接由于流量、连接问题等原因很慢),那么他们会继续前进,但品牌会被抛在后面,并且一切都不同步。
我从 app.component.ts 中的服务调用加载品牌:
ngOnInit() {
// Get the brand for the first time
this.brandService.getBrand(window.location.origin);
console.log(new Date().toString(), 'AppComp => this.brandService.getBrand()');
}
调用本身并没有什么特别之处:
// Get a Brand into cache
getBrand(url: string) {
this.brandRequest = {
Url: url,
BrandLookupType: 'review'
};
this.http.post<BrandLookup>(this.api + this.controller + 'getbrandlookup', this.brandRequest).subscribe(res => {
console.log(new Date().toString(), this.constructor.name, '=> getBrand()', res);
this.brandLookup = res;
const bronzeMin = this.brandLookup.pricingMatrix.singleWillPrice;
const silverMin = this.brandLookup.pricingMatrix.singleWillPrice + this.brandLookup.pricingMatrix.lifetimeInterestPrice;
const goldMin = this.brandLookup.pricingMatrix.singleDWTPrice;
localStorage.setItem('brandCode', this.brandLookup.brandCode);
localStorage.setItem('ssoUrl', this.brandLookup.ssoUrl);
localStorage.setItem('cpUrl', this.brandLookup.customerPortalUrl);
localStorage.setItem('reviewUrl', this.brandLookup.reviewUrl);
localStorage.setItem('brand', JSON.stringify(this.brandLookup.brand));
// Set Bronze Landing Page price
if (bronzeMin === null) {
localStorage.setItem('bronzeMin', '89');
} else {
localStorage.setItem('bronzeMin', bronzeMin.toString());
}
// Set Silver Landing Page Price
if (silverMin === null) {
localStorage.setItem('silverMin', '239');
} else {
localStorage.setItem('silverMin', silverMin.toString());
}
// Set Gold Landing Page Price
if (goldMin === null) {
localStorage.setItem('goldMin', '550');
} else {
localStorage.setItem('goldMin', goldMin.toString());
}
this.broadcastBrandUpdate();
});
}
我基本上需要一种方法来阻止 DOM 在屏幕上加载,直到这个调用完成 - 有没有办法在 Angular 中做到这一点?
解决方案
我们可以在这里做两件事——
首先,让我告诉您我从您的问题中理解的内容-您不希望用户在未加载品牌之前单击任何地方,仅此而已。
- 最好的解决方案是显示全屏加载程序,直到品牌 API 没有返回数据。一旦你有数据隐藏加载器并让用户点击任何地方。
- 使用解析器保护并在解析器中调用您的品牌 API,解析器将保护您的屏幕,直到品牌 API 不成功,您的屏幕才会加载。
我添加了一些很好的资源来学习如何在您的应用程序中实现解析器防护。
推荐阅读
- python - 使用带有 kind='reg' 的 seaborn pairplot 时出现轴限制问题
- clasp - 检索访问令牌时出错:TypeError:无法读取未定义的属性“project_id”
- python - Python。如何使用步骤(块)读取文件而不重写每个块?
- zsh - 查找具有最高(纯数字)文件名的文件
- angular - 初始化时未选择 Angular 7 SELECT 选项
- python - 热方程 - 设置和绘图
- xamarin.forms - 如何从 xamarin 表单将多个对象发布到 webapi
- c# - 违反 PRIMARY KEY 约束“PK_EMPLOYEE”。无法在对象中插入重复键
- javascript - 为什么我更新的对象没有出现在状态中?
- c# - 为什么要在 C# 中定义一个本地函数只是为了立即调用它(在 IEnumerable 的上下文中
)