angular - 数据更改时重新创建组件

标签 angular typescript rxjs rxjs5

好吧,这个问题似乎有很多答案,但我一直无法理解我应该做什么。

我目前有一个子组件,当有人点击另一个子组件的播放按钮时,该子组件就会被创建。这是通过与我的 parent 共享数据的服务发生的,然后 parent 传递数据并创建我的子音频播放器组件。我遇到的问题是,如果用户导航到另一个页面并单击以播放该页面上的音频,旧音频仍然存在并且新音频不会启动。

是否有生命周期 Hook 或方法可用于销毁我的旧音频组件并创建新的音频 onclick?

信息框 - 单击播放按钮时初始激活发生的地方。

export class InfoBoxComponent implements OnInit {
  ...

  activateAudioPlayer(session) {
    this.newAudioService.newAudio(session)
  }
}

新的音频服务

export class NewAudioService {
  newActiveAudioSource: Subject<string> = new Subject<string>();

  newAudio(session) {
    this.newActiveAudioSource.next(session);
  }

  newActiveAudio$ = this.newActiveAudioSource.asObservable();
}

前端组件 - 信息框和音频播放器的父组件

@Component({ 
   template: `<audio-player *ngIf='newActiveAudio' [newActiveAudio]='newActiveAudio'></audio-player>`,
})

export class FrontendComponent implements OnInit {

  ...

  ngOnInit() {
    this.sub = this.newAudioService.newActiveAudio$.subscribe(
      newActiveAudio => {
        this.newActiveAudio = newActiveAudio;
      });
  }

  ngOnDestroy() {
    // prevent memory leak when component destroyed
    this.sub.unsubscribe();
  }
}

最佳答案

这是一个小指令,当 key 值改变时重新创建 View :

import {
  Directive,
  EmbeddedViewRef,
  Input,
  OnChanges,
  SimpleChanges,
  TemplateRef,
  ViewContainerRef
} from '@angular/core';

@Directive({
  selector: '[wRecreateViewKey]'
})
export class RecreateViewDirective implements OnChanges {
  @Input('wRecreateViewKey') key: any;

  viewRef: EmbeddedViewRef<any>;

  constructor(private templateRef: TemplateRef<any>, private viewContainer: ViewContainerRef) {}

  ngOnChanges(changes: SimpleChanges): void {
    if (changes.key) {
      if (this.viewRef) {
        this.destroyView();
      }

      this.createView();
    }
  }

  private createView() {
    this.viewRef = this.viewContainer.createEmbeddedView(this.templateRef);
  }

  private destroyView() {
    this.viewRef.destroy();
    this.viewRef = null;
  }
}

使用示例:

<!-- `some-component` will be destroyed and recreated every time `value` changes. -->

<some-component *wRecreateViewKey="value"></some-component>

<!-- Can also be used on regular DOM elements or container -->
<div *wRecreateViewKey="value"></div>
<ng-container *wRecreateViewKey="value"></ng-container>

关于angular - 数据更改时重新创建组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41402798/

相关文章:

angular - 为什么 PrimeNG p-calendar 不显示日期值?

javascript - Typescript typecast object 所以特定的必需键在类型中不再是可选的?

angular - 如何启用和禁用基于选择表单的垫按钮

javascript - Ionic - Angular - 组件的三个输入中有两个具有未定义的值

node.js - 在 mac 中缺少对/usr/local/lib/node_modules 的写访问

typescript - Make 函数参数只接受来自变量对象的键

angular - 类型 'valueChanges' 上不存在属性 'Observable<any>'

meteor - Angular2-Meteor zone() 方法

angular - 使用 RxJS 的 Promise.all()

Angular/rxjs/Subject/BehaviorSubject跨多个组件共享http服务数据