【问题标题】:Angular UpgradeComponent cannot find $scopeAngular UpgradeComponent 找不到 $scope
【发布时间】:2017-09-01 22:43:57
【问题描述】:

我有一个混合 angular-cli,大致遵循 Victor Savkin 的Lazy Loaded AngularJS guide。 AngularJS 在 LazyLoaded Angular 模块的构造函数中被引导。我的应用程序和指南之间的主要区别在于我试图将 <ui-view> 指令包装在一些 Angular 组件中。由于我的布局结构,<ui-view> 元素在 AngularJS 启动时将不可用,并且可以随时添加或删除。

import { Component, Directive, ElementRef, Injector } from '@angular/core';
import { UpgradeComponent } from '@angular/upgrade/static';
import * as angular from 'angular';

@Component({
  template: `
  <layout-wrapper>
    <my-toolbar></my-toolbar>
    <layout-contents>
      <ng2-ui-view>
        <h3 class="text-center">AngularJS page not loaded</h3>
      </ng2-ui-view>
    </layout-contents>
  </layout-wrapper>
  `,
})
export class LegacyOutputComponent { }

@Directive({selector: 'ng2-ui-view'})
export class UpgradedUiViewComponent extends UpgradeComponent {
  constructor(ref: ElementRef, inj: Injector) {
    super('uiViewWrapper', ref, inj);
  }
}

export const routerPatchModule = 'arcs.router.patch';

// We need to define a wrapper for ui-view because we can only upgrade
// components with only one definition. uiView cannot be automatically
// upgraded because its definition is too complex
angular.module(routerPatchModule, ['ui.router'])
.component('uiViewWrapper', { template: '<ui-view></ui-view>'})

当我运行代码时,会抛出 Error: No provider for $scope! 错误。检查堆栈跟踪我可以看到它是在UpgradeComponent 超类中抛出的。注入器尝试获取$scope

【问题讨论】:

    标签: angularjs angular angular-upgrade


    【解决方案1】:

    另一种方法是让 Angular 知道它需要提供$scope

    import { Injector } from '@angular/core';
    
    // allow $scope to be provided to ng1
    export const ScopeProvider = {
      deps: ['$injector'],
      provide: '$scope',
      useFactory: (injector: Injector) => injector.get('$rootScope').$new(),
    };

    @Directive({
      providers: [ ScopeProvider ],
      selector: 'ng2-ui-view',
    })
    export class UpgradedUiViewComponent extends UpgradeComponent {
      constructor(ref: ElementRef, inj: Injector) {
        super('uiViewWrapper', ref, inj);
      }
    }

    【讨论】:

    • 感谢 V,帮助了我:+1
    【解决方案2】:

    此设置将不起作用。 AngularJS 需要能够加载到应用程序的根目录中才能正确定义范围。

    解决此问题的更好方法是在应用程序的根目录中使用 &lt;div ui-view&gt; 指令(如升级指南中所述),然后将布局组件从 Angular 降级为 AngularJS 以包装您的内容。

    【讨论】:

    • Vizjerai 的建议仍然适用于解决运行时 'NullInjectorError: No provider for $scope!'浏览器错误。
    猜你喜欢
    • 2018-10-26
    • 2015-03-16
    • 2014-09-13
    • 2016-08-31
    • 2017-06-23
    • 2016-03-21
    • 1970-01-01
    • 1970-01-01
    • 2017-05-10
    相关资源
    最近更新 更多