Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

Remove One Item From Array In BehaviorSubject Angular/Typescript

I am trying to remove a specific element from my array when the user clicks it however, it seems to be deleting them all. I have tried using splice on the dataService specifically but I am not able to do that, I get an error saying "Property 'splice' does not exist on type 'Observable< any>'" I am trying to figure out how to remove one element from the dataService specifically, based off of the Object passed to it from the HTML. Any tips would be greatly appreciated! 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);
  }

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can instead try this:

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

What I did was, I passed the index on the button click, and spliced using the index. Try this and see if it works for you.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...