我在项目中使用bodymovin脚本。即使我的某些动画SVG在浏览器中呈现,我仍然会收到此错误

Uncaught TypeError: Cannot read property 'appendChild' of undefined
    at SVGRenderer.configAnimation (bodymovin.min.js:5)
    at AnimationItem.configAnimation (bodymovin.min.js:9)
    at XMLHttpRequest.r.onreadystatechange (bodymovin.min.js:9)
    at XMLHttpRequest.wrapFn [as __zone_symbol___onreadystatechange] (zone.js:1075)
    at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:424)
    at Zone.webpackJsonp.../../../../zone.js/dist/zone.js.Zone.runTask (zone.js:191)
    at ZoneTask.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneTask.invokeTask [as invoke] (zone.js:498)
    at invokeTask (zone.js:1370)
    at XMLHttpRequest.globalZoneAwareCallback (zone.js:1388)


根据this answer,我认为应该在页面上的所有内容加载后运行bodymovin脚本。考虑到新建议,我已经更新了代码

index.html

<!doctype html>
<html lang="en">
<head>...</head>
<body>...
<div class="full-app-body">
   <app-root></app-root>
  </div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bodymovin/4.10.2/bodymovin.min.js"></script>
</body>
</html>


app.component.ts

import { Component, ElementRef, OnInit, AfterViewInit } from '@angular/core';
import { Router, ActivatedRoute, RouterOutlet, Routes } from '@angular/router';
import { BrowserModule } from '@angular/platform-browser';
import { NgClass, CommonModule } from '@angular/common';
...

export class AppComponent implements AfterViewInit {
  constructor(public router: Router, private elementRef: ElementRef) {}
...
  ngAfterViewInit() {
    const s = document.createElement('script');
    s.type = 'text/javascript';
    s.src = '/assets/js/animations.js';
    // this.elementRef.nativeElement.appendChild(s);
    document.body.appendChild(s);
  }


app.component.html

<div id='bm'></div>


animations.js

var animation = bodymovin.loadAnimation({
  container: document.getElementById('bm'),
  renderer: 'svg',
  loop: true,
  autoplay: true,
  path: './assets/images/ani/fatigue-data.json'
});

最佳答案

据我了解,问题出在this.elementRef.nativeElement.appendChild(s);行上。您正在尝试将某些内容附加到未知元素.U应该获得对您尝试将脚本附加到该元素的元素的引用。由于仅需添加脚本,请尝试以下代码

 document.body.appendChild(s);


希望这会有所帮助

更新

由于您使用的是角度4,因此可以按照建议的here使用Renderer2来解决您的目的

10-08 11:46