首页 > 解决方案 > 是否有一种标准方法可以让 AngularJS 在动态加载时检测 UpgradeComponent 的初始值?

问题描述

背景信息: 之前在这个 github 问题UpgradeComponent中提出了一个相当常见的问题,即在动态加载的入口组件中使用 s 时出现注入器错误。我觉得我对此理解得很好,并且能够通过使用与此答案类似的解决方案来正确注入范围:

export const ScopeProvider = {
  deps: ['$injector'],
  provide: '$scope',
  useFactory: scopeFunction,
};

export function scopeFunction(i: any) {
  const newScope = i.get('$rootScope').$new();

  // special property to differentiate this scope from the one coming
  // from the injector that is not used for dynamically loaded components
  newScope.dynamicScope = true;

  return newScope;
}

我绝对想知道这个解决方案是否存在我不知道的陷阱,而不是github 问题中提到的注入器解决方案。

但是,这不是我主要关心的问题。我主要担心的是,即使使用正确的Injectorand ScopeUpgradeComponent仍然存在组件上的初始值没有被 angularjs 检测到的问题,因为$digest在创建组件后没有发生任何事情。这可能是组件加载器的具体问题ngx-bootstrap,而不是 angular 的一般问题,但我目前不确定。我现在想出的解决方法是Scope.$evalAsync()在构造函数的末尾调用UpgradeComponent,但我不确定这是否是正确的方法,这就是我问这个问题的原因。

这是我修复的逻辑示例:

export class Testng1ComponentFacade extends UpgradeComponent implements OnInit {

  constructor(elementRef: ElementRef, injector: Injector) {
    super(testng1Component.selector, elementRef, injector);

    const injectorScope = injector.get('$scope');
    if(injectorScope.dynamicScope) {
      console.log('calling $evalAsync() for UpgradeComponent');
      injectorScope.$evalAsync(() => {});
    }
  }

}

我有点基于这个角度代码

TL; DR: 这也是这个问题的简单重现,包括我的修复。

标签: angularngx-bootstrapng-upgradeangular-upgradengx-bootstrap-modal

解决方案


推荐阅读