Angular Universal和ElementRef / Renderer2.createElement

时间:2018-01-10 21:00:42

标签: node.js angular angular-universal

我已使用此处列出的步骤将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不是函数?

1 个答案:

答案 0 :(得分:2)

我找到了解决方案。您无法在服务中直接使用Renderer2,因此我使用了此处的RendererFactory2建议:Renderer cannot be used in Service?

然后我更改了这一行:

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

到此:

this.renderer2.appendChild(this._document.head, node);
相关问题