【问题标题】:Angular Universal and ElementRef/Renderer2.createElementAngular Universal 和 ElementRef/Renderer2.createElement
【发布时间】:2018-06-20 03:06:02
【问题描述】:

我已使用此处概述的步骤将 Angular 5 应用程序移植到 Angular Universal:https://angular.io/guide/universal

我正在尝试移植文档和窗口的某些用途。它构建得很好,但现在我得到了这个运行时错误:

    ERROR { Error: Uncaught (in promise): Error: StaticInjectorError[LayoutDirective -> ElementRef]: 
  StaticInjectorError(Platform: core)[LayoutDirective -> ElementRef]: 
    NullInjectorError: No provider for ElementRef!

我的一个 Karma 测试显示了类似的错误:

Chrome 63.0.3239 (Mac OS X 10.13.2) MyComponent should create FAILED
        Error: StaticInjectorError(DynamicTestModule)[MatIcon -> ElementRef]:
          StaticInjectorError(Platform: core)[MatIcon -> ElementRef]:
            NullInjectorError: No provider for ElementRef!
            at _NullInjector.webpackJsonp.../../../core/esm5/core.js._NullInjector.get Users/project/node_modules/@angular/core/esm5/core.js:994:1)

我相信这是破坏事物的代码(旧版本已注释掉);

    @Injectable()
    export class MyService {
        @ViewChild('head') headEl: ElementRef;

...
    return Observable.create((observer: Observer<boolean>) => {
                // const node = document.createElement('script');
                const node = this._renderer2.createElement('script');


                node.src = this.url;
                node.type = 'text/javascript';
                node.charset = 'utf-8';

                // document.getElementsByTagName('head')[0].appendChild(node);
                this._renderer2.appendChild(this.headEl, node);

                node.onload = () => {
                    observer.next(true);
                    observer.complete();
                };
            });

编辑:现在我看到了这个错误:

Failed: _this._renderer2.createElement is not a function
        TypeError: _this._renderer2.createElement is not a function

为什么 renderer2.createElement 不是函数?

【问题讨论】:

    标签: node.js angular angular-universal


    【解决方案1】:

    我找到了解决方案。你实际上不能直接在服务中使用 Renderer2,所以我使用了这里的 RendererFactory2 建议:Renderer cannot be used in Service?

    然后我改变了这一行:

    this.renderer2.appendChild(this.headEl, node);
    

    到这里:

    this.renderer2.appendChild(this._document.head, node);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-02
      • 1970-01-01
      • 2021-10-04
      • 1970-01-01
      • 2018-06-01
      • 2019-01-16
      • 2017-02-08
      • 2018-08-20
      相关资源
      最近更新 更多