视频html播放与angular2+;使用通用SSR的指令

视频html播放与angular2+;使用通用SSR的指令,html,angular,typescript,html5-video,angular-directive,Html,Angular,Typescript,Html5 Video,Angular Directive,我目前正在尝试实现一个Angular指令,自动静音并播放HTML5视频标签 我在Angular 10中运行此代码。这个错误发生在我测试的所有浏览器中 这是我的密码 您的浏览器不支持视频标记。 指令组件看起来像 import { Directive, ElementRef, OnInit} from '@angular/core'; @Directive({ selector: '[appVideoAutoplayMuted]' }) export class VideoAutoplay

我目前正在尝试实现一个Angular指令,自动静音并播放HTML5视频标签

我在Angular 10中运行此代码。这个错误发生在我测试的所有浏览器中

这是我的密码


您的浏览器不支持视频标记。
指令组件看起来像

import { Directive, ElementRef, OnInit} from '@angular/core';

@Directive({
  selector: '[appVideoAutoplayMuted]'
})
export class VideoAutoplayMutedDirective implements OnInit {

  constructor(public videoElement: ElementRef) {
  }

  ngOnInit(): void {
    const video: HTMLVideoElement = this.videoElement.nativeElement;
    video.muted = true;
    video.play(); // play is not a function exception
  }
}
当代码到达
video.play()时行它崩溃给我下一个错误

错误类型错误:video.play不是一个函数

我调试了代码,视频常量不是空的,他的类型是HTMLVideoElement

智能感知也在发挥作用。我发现这个函数是存在的


我找到了解决办法。问题是代码是在服务器端调用的,因为我使用的是Angular Universal。我不知道为什么,但似乎服务器中的HTMLVideoElement没有
play()
load()
和其他方法。我认为这种方法是通过浏览器实现的

我通过在指令中运行if语句解决了检查代码在哪里的问题

import {Directive, ElementRef, Inject, OnInit, PLATFORM_ID} from '@angular/core';
import {isPlatformBrowser} from '@angular/common';

@Directive({
  selector: '[appVideoAutoplayMuted]'
})
export class VideoAutoplayMutedDirective implements OnInit {

  constructor(public videoElement: ElementRef, @Inject(PLATFORM_ID) private platformId: any) {
  }

  ngOnInit(): void {
    if (isPlatformBrowser(this.platformId)) { // here is the check 
      const video: HTMLVideoElement = this.videoElement.nativeElement;
      video.muted = true;
      video.play();
    }
  }
}
请随意扩展此答案,以便我们更好地了解正在发生的事情