Home > Enterprise >  Array doesnt refresh, tried many methods
Array doesnt refresh, tried many methods

Time:11-10

I'm trying to delete item in single item view and refresh component that displays list: Im quite sure that I'm changing reference of table, but it simply doenst help. Im new to angular, could lazy loading cause this? I can see my angular version is 14.2.9

Service:

import { EventEmitter, Injectable, Output } from '@angular/core';
import { Hero } from './hero';
import { HEROES } from './mock-heroes';
import { Observable, of } from 'rxjs';
import { MessageService } from './message.service';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Customer } from './customers/Customer';
import {PaginatedResult} from '../app/shared/model/PaginationResult'

@Injectable({
  providedIn: 'root'
})
export class HeroService {

  @Output() aClickedEvent = new EventEmitter<number>();

 

  constructor(private http: HttpClient, private messageService: MessageService) { }

  page: number = 0;

  getHeroes(page: number): Observable<PaginatedResult<Customer>> {

    if(page == 0 ) {

    } else {
      page = page -1;
    }

    return this.http.get<PaginatedResult<Customer>>('http://localhost:8080/customer'   '?page='   page  '&limit=10')
  }

 

  deleteCustomer(id?: number): Observable<Customer> {

    this.aClickedEvent.emit(data);    

    return this.http.delete<Customer>('http://localhost:8080/user/'   id);
  }

}

List component:

import { ChangeDetectionStrategy, Component, NgZone, OnInit } from '@angular/core';
import { HeroService } from '../../hero.service';
import { MessageService } from '../../message.service';
import { Customer } from '../Customer';

@Component({
  selector: 'app-heroes',
  templateUrl: './heroes.component.html',
  styleUrls: ['./heroes.component.css'],
  changeDetection: ChangeDetectionStrategy.Default

})
export class HeroesComponent implements OnInit {
  users:Customer[] = [];
  users2:Customer[] = [];

  p: number = 0;
  total: number = 0;

  constructor(private zone: NgZone,private heroService: HeroService, private messageService: MessageService) { 
   ;
  } 

  
  
  selectedHero?: Customer;
  onSelect(hero: Customer): void {
    this.messageService.add(`HeroesComponent: Selected hero id=${hero.id}`);

    this.selectedHero = hero;
  }
  ngOnInit(): void {

    this.heroService.aClickedEvent
    .subscribe((data:number) => {
      this.users = this.users.filter(a => 
        a.id !== data
      )
      console.log(this.users);

      this.users = [...this.users]
    });

    this.getUsers();
  }

  getUsers(){
    this.heroService.getHeroes(this.p)
      .subscribe((response: any) => {
        console.log(response);
        this.users = response.results;
        this.total = response.totalCount;
      });
} 

pageChangeEvent(event: number){
  console.log(event);
  this.p = event;
  this.getUsers();
}



}

List html :





<div  >
  <div  >
    <!-- Your first column here -->
   
  <table style="float: left" >
    <thead>
    <tr>
      <th>ID</th>
      <th>First Name</th>
      <th>Last Name</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let user of users | paginate: { itemsPerPage: 10, currentPage: p, totalItems: total  }"
    routerLink="detail/{{user.id}}">
        <td>{{ user.id }}</td>
        <td>{{ user.firstName }}</td>
        <td>{{ user.lastName }}</td>
    </tr>
  </tbody>
  </table>  
  <pagination-controls (pageChange)="pageChangeEvent($event)"></pagination-controls>
</div>  
<!-- <div >
  <app-hero-detail [customer]="selectedHero"></app-hero-detail>
</div>
</div> -->

Detail component:

import { Component, OnInit, Input } from '@angular/core';
import { Customer } from '../Customer';
import { ActivatedRoute } from '@angular/router';
import { Location } from '@angular/common';
import { HeroService } from 'src/app/hero.service';

@Component({
  selector: 'app-hero-detail',
  templateUrl: './hero-detail.component.html',
  styleUrls: ['./hero-detail.component.css']
})
export class HeroDetailComponent implements OnInit {
  @Input() customer?: Customer;
  
  constructor(private route: ActivatedRoute,
    private heroService: HeroService,
    private location: Location) { }

  ngOnInit(): void {
      this.getCustomer();
    }

  getCustomer(): void {
    const id = Number(this.route.snapshot.paramMap.get('id'));
    this.heroService.getCustomer(id)
      .subscribe(customer => this.customer = customer);
  }

  goBack(): void {
    this.location.back();
  }

  delete(id?:number):void {
    this.heroService.deleteCustomer(id)
    .subscribe(string => {});

    this.location.back();
  }

  edit() {

  }
}

Detail html

<div >


<div *ngIf="customer" >
    <div  style="max-width: 550px; margin-left: 25%;">
        <h2 style="text-align:center;"><b>{{customer.firstName}} {{customer.lastName}}</b></h2>
        <p style="text-align:center;">Address</p>
        <h2 style="text-align:center;"><b>{{customer?.address?.street}} {{customer.lastName}}</b></h2>
      <div >
        <button  type="button" (click)="goBack()" style="margin-left:40px">Back</button>
        <button  type="detai" (click)="edit()" style="margin-left:100px">Edit</button>
        <button   type="button" (click)="delete(customer!.id)" style="margin-left:100px">Delete</button>
      </div>
    </div>
  
  </div>
</div>

CodePudding user response:

Here is how you should make it work.

Edit:

delete(id?:number):void {
    this.heroService
        .deleteCustomer(id)
        .subscribe(() => {
            this.heroService.aClickedEvent.emit(id);
            this.location.back();
        });
  }

And

@Output() public aClickedEvent = new EventEmitter<number>();

And in service's delete method, remove this.aClickedEvent.emit(data);

  • Related