【问题标题】:Angular component isnt passing data before the child component is loadedAngular 组件在加载子组件之前未传递数据
【发布时间】:2020-11-16 01:11:36
【问题描述】:

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

子组件

  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;

父模板

这有点谈到我的问题,但考虑到数据已更改,我的问题更复杂 Angular 2 child component loads before data passed with @input()

【问题讨论】:

  • console.log(this.currentTurnName);它是否记录 currentTurnName 的值?
  • 所以注释掉的 ngOnChanges 也不起作用..? console.logs 显示了什么?
  • 示例中缺少您的代码的一些相关部分。你能再充实一点吗?

标签: javascript angular


【解决方案1】:

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

这是使用您的代码的 sn-p:

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);
  }
}

【讨论】:

    猜你喜欢
    • 2017-01-02
    • 2017-05-13
    • 2021-04-02
    • 1970-01-01
    • 2020-07-23
    • 2022-01-19
    • 2021-03-03
    • 2017-08-12
    相关资源
    最近更新 更多