首页 > 解决方案 > 在 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 中做到这一点?

标签: angular

解决方案


我们可以在这里做两件事——

首先,让我告诉您我从您的问题中理解的内容-您不希望用户在未加载品牌之前单击任何地方,仅此而已。

  1. 最好的解决方案是显示全屏加载程序,直到品牌 API 没有返回数据。一旦你有数据隐藏加载器并让用户点击任何地方。
  2. 使用解析器保护并在解析器中调用您的品牌 API,解析器将保护您的屏幕,直到品牌 API 不成功,您的屏幕才会加载。

我添加了一些很好的资源来学习如何在您的应用程序中实现解析器防护。

https://angular.io/api/router/Resolve

https://www.bacancytechnology.com/blog/angular-resolver


推荐阅读