当 dataService 中的数据发生变化时更新组件

时间:2021-01-13 02:30:20

标签: angular typescript components

我正在尝试更新所有组件以反映对 dataService 所做的更改,目前当我向列表中添加一个项目时,它会显示在页脚中(页脚区域为纯绿色)

displayed in footer

但是,如果我单击删除按钮,它会从页脚中删除(页脚区域为纯绿色),但不会更新正文组件(当项目从列表中删除时,按钮应从已提名更改回提名)

enter image description here

我该如何解决这个问题,以便在点击删除按钮时,提名按钮也会更新?谢谢!

我有 3 个组件堆叠如下:

<app-header></app-header>
<app-footer></app-footer>
<app-body></app-body>

在我的footer.component.ts里面

import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';

@Component({
  selector: 'app-footer',
  templateUrl: './footer.component.html',
  styleUrls: ['./footer.component.css']
})
export class FooterComponent {

  nominations = [];

  constructor(private dataService: DataService) {
    this.dataService.nominations.subscribe(noms => this.nominations.push(noms));
    this.nominations.splice(0, 1);
  }

  ngOnInit(): void{
    
  }

  remove(indx: number){
    //remove movie from array in footer
    this.nominations.splice(indx, 1);
    //remove movie from dataService
    delete this.dataService.nominations[indx];
  }

}

在我的 body.component.ts 里面

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { DataService } from '../data.service';
@Component({
  selector: 'app-body',
  templateUrl: './body.component.html',
  styleUrls: ['./body.component.css']
})
export class BodyComponent implements OnInit {

  movies: string[];
  inptMovie = "";
  nominations = [];

  constructor(private http: HttpClient, private dataService: DataService) {
    this.dataService.nominations.subscribe(noms => this.nominations.push(noms));
    this.nominations.splice(0, 1);
   }

  ngOnInit(): void{
    
  }

  //check to see if the movie is already nominated.
  checkNominations(mov: Object){
    let arr = [];   
    arr.push(mov);
    var isInArray = this.nominations.find(e => e.imdbID === arr[0].imdbID) !== undefined;
    return isInArray;
  }

}

在 body.component.html 内

<!-- creating area to display movies -->
<div class="movieDisplay">
    <div id="display" *ngFor="let mov of movies">
        <img src={{mov.Poster}}/>
        <br><br><br>
        <h3>{{mov.Title}}</h3>
        <p>{{mov.Year}}</p>
        <!-- Show a clickable button if movie isnt in list, and disabled button if it is in the list -->
        <button type="submit" *ngIf="!checkNominations(mov); else nominated" (click)="nominate(mov)">Nominate</button>
        <ng-template #nominated><button type="submit" disabled="True">Nominated!</button></ng-template>
    </div>
</div>

0 个答案:

没有答案