繁体   English   中英

Angular 组件在加载子组件之前未传递数据

[英]Angular component isnt passing data before the child component is loaded

在我的代码中,我有一个组件保存从 firebase 检索到的所有数据。 包括一个名为“currentTurnName”的变量,它从父组件传递到子组件。 该变量用于在子组件内呈现抽搐通道,但不会在数据更改时更新。我遵循了一些堆栈溢出指南,讨论了使用 *ngIf 指令(如 <childComponent *ngIf"currentTurnName"> 停止子组件从加载到检索到数据 - 它在页面加载时工作,除非当该变量异步传递新数据时它不起作用。

子组件

  export class TwitchVideoComponent implements OnInit {
  constructor() { 
  }

  player: any;
  @Input() currentTurnName: any;

  ngOnInit(): void {
      var options = {
        width: 1080,
        height: 720,
        channel: this.currentTurnName,
      };
      this.player = new Twitch.Player("<player div ID>", options)
      this.player.setVolume(0.5);
      console.log(this.currentTurnName);
  }
//  ngOnChanges(changes: SimpleChanges) {
//    if (this.currentTurnName) {
//     this.player.setChannel(this.currentTurnName);
//    }
//  }
}

子模板

 <div id="<player div ID>" class="twitch"></div>

父组件

  export class GameRoomComponent implements OnInit {
  public  users$: Observable<User[]>
  currentUser: Observable<CurrentUser[]>;

  constructor(private usersService: UsersService, private afs: AngularFirestore) { 
    this.currentTurn = afs.collection<CurrentUser>('currentPlayerDB').valueChanges().pipe(
      tap(res => {
        this.currentTurnName = res[0].user;
        console.log(this.currentTurnName);
      })
    ).subscribe();
  }
  currentTurn: any;
  items: any;
  currentTurnName : any;

父模板

<app-twitch-video *ngIf="currentTurnName" [currentTurnName]="currentTurnName" >

这有点谈到我的问题,但考虑到数据已更改,我的问题更复杂Angular 2 子组件在通过@input() 传递数据之前加载

您可以使用 Angular 的属性设置器。 可以在本节中找到文档(使用 setter 拦截输入属性更改): https://angular.io/guide/component-interaction

这是使用您的代码的片段:

export class TwitchVideoComponent implements OnInit {
 constructor() {}

 player: any;

 @Input() set currentTurnName(name) {
   this._currentTurnName = name;
   console.log('This should fire every time this Input updates', this._currentTurnName);
   if (this._currentTurnName) {
    this.player.setChannel(this._currentTurnName);
   }
 }

 public _currentTurnName: any;

  ngOnInit(): void {
    var options = {
      width: 1080,
      height: 720,
      channel: this._currentTurnName,
    };
    this.player = new Twitch.Player("<player div ID>", options)
    this.player.setVolume(0.5);
    console.log(this._currentTurnName);
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM