【问题标题】:Remove One Item From Array In BehaviorSubject Angular/Typescript从 BehaviorSubject Angular/Typescript 中的数组中删除一项
【发布时间】:2021-04-03 06:46:38
【问题描述】:

当用户单击它时,我试图从我的数组中删除一个特定元素,但是,它似乎将它们全部删除。我曾尝试在 dataService 上专门使用 splice,但我无法做到这一点,我收到一条错误消息,提示“'Observable' 类型上不存在属性 'splice'”我试图弄清楚如何删除一个具体来说,来自 dataService 的元素,基于从 HTML 传递给它的 Object。任何提示将非常感谢! footer.component.ts

export class FooterComponent {
  nominations = [];
  constructor(private dataService: DataService) {
    this.dataService.currentNoms.subscribe(noms => {this.nominations.push(noms);});
  }
  ngOnInit(): void{
    
  }
  remove(nom: Object): any{
    this.nominations.splice(this.nominations.indexOf(nom), 1);
    console.log(nom);
    console.log(this.nominations);      
  }

}

footer.component.html

<div class="nominationsDisplay">
    <div id="nominations" *ngFor="let nom of nominations[0]">
        <img src={{nom.Poster}}/>
        <button class="removeBtns" type="submit" (click)="remove(nom)">Remove</button>
    </div>
</div>

data.service.ts

export class DataService {

  private finalNoms = new BehaviorSubject<any>([]);
  currentNoms = this.finalNoms.asObservable();

  constructor() { }

  addNominations(nom: Object){
    this.finalNoms.next(nom);
  }

}

【问题讨论】:

    标签: angular typescript angular-components


    【解决方案1】:

    你可以试试这个:

    footer.component.html

    <div class="nominationsDisplay">
        <div id="nominations" *ngFor="let nom of nominations[0]; let i = index">
            <img src={{nom.Poster}}/>
            <button class="removeBtns" type="submit" (click)="remove(i)">Remove</button>
        </div>
    </div>
    

    TS File

    remove(index: number): any{
        this.nominations.splice(index, 1);
        console.log(nom);
        console.log(this.nominations);      
      }
    

    我所做的是,我在按钮单击时传递了索引,并使用索引进行拼接。试试这个,看看它是否适合你。

    【讨论】:

    • 谢谢!这会将其从 footer.component.ts 中的数组中删除,但我现在需要弄清楚如何从我在组件之间使用的 data.service.ts 数组中删除它。 currentNoms 是我需要从中删除项目的数组,但我似乎无法弄清楚。
    • 您可以通过使用索引来查找检索数组中存在的 Nominations 对象并使用该 ID,然后使用服务将其删除。
    【解决方案2】:

    您可以简单地删除 service.ts

    中的项目
    export class DataService {
    
      private finalNoms = new BehaviorSubject<any>([]);
      currentNoms = this.finalNoms.asObservable();
    
      constructor() { }
    
      addNominations(nom: Object){
        this.finalNoms.next(nom);
      }
    
      removeNominations(nom: Object) {
        const newArray = [...this.finalNoms.value];
        newArray.splice(this.nominations.indexOf(nom), 1);
        this.finalNoms.next(newArray)
      }
    
    }
    

    在您的 FooterComponent.ts

      remove(nom: Object): any{
        this.dataService.removeNominations(nom)     
      }
    

    现在所有订阅者都会收到此更改的通知

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-02-23
      • 1970-01-01
      • 2021-03-27
      • 2013-11-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多