Home > Net >  Im pushing to array by service, but its not visible Angular
Im pushing to array by service, but its not visible Angular

Time:10-02

Im pushing im trying to push data from Reactive form in one component to service and then output this in mat-table, the problem is it works, when im cl('array','data') everything lookis fine but its not vissible from the website.

ts.

onSubmit() {
    const singleJob: Job = {
      name: this.signupForm.controls['jobsName'].value,
      points: this.signupForm.controls['jobPoints'].value,
    };
    this.dataService.pushToJobs(singleJob);
  }
  addUser() {
    const singleUser: User = {
      name: this.signupForm.controls['userName'].value,
    };
    this.dataService.addUser(singleUser);
  }

service.ts

export class DataService {
  jobs: Job[] = [
    { name: 'sprzatanie', points: 10 },
    { name: 'gotowanie', points: 20 },
    { name: 'mycie okien', points: 30 },
    { name: 'wyniesc smieci', points: 10 },
    { name: 'zmywanie', points: 50 },
  ];
  userJobs: Job[] = [{ name: 'test1', points: 7 }];
  users: User[] = [{ name: 'Karol' }];
  constructor(private logic: LogicService) {}

  pushToJobs(userjob: Job) {
    this.jobs.push(userjob);
    console.log(userjob, this.jobs);
  }
  pushToUserJobs() {}
  addUser(user: User) {
    this.users.push(user);
    console.log(user, this.users);
  }
}

CodePudding user response:

I assume your mat-table consumes the data like this

<mat-table [dataSource]="userJobs>...</mat-table>

Your component

export class YourComponent {
  constructor(
    private readonly _dataService: DataService,
  ) {
    this.userJobs = this._dataService.userJobs;
  }
}

Given this code the problem is that mat-table stores (and updates) the array by reference. Since you just add data to the array, this reference does not change (even though its stored values may). Therefore you should just create a new array when adding items to the existing array like so:

private _userJobs = [];
userJobs$ = BehaviorSubject(this._userJobs);

pushToUserJobs(userjob: UserJob) {
  this._userJobs = [...this.userJobs, userjob];
  userJobs$.next(this._userJobs);
}

and

<mat-table [dataSource]="userJobs$ | async>...</mat-table>

Here's a proof of concept on Stackblitz: https://stackblitz.com/edit/angular-tnb33i

  • Related