I am having a service that insert data in an array ( list ). service.ts code is below. Problem: Data gets passed to service from component but after push to array it becomes null
import { Injectable } from '@angular/core';
import { User } from '../models/user.model';
import { Observable, of } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class UserService {
private users: User[] = [
{ id: 1, name: 'John Doe', email: '[email protected]', phone: '123-456-7890' },
{ id: 2, name: 'Jane Smith', email: '[email protected]', phone: '987-654-3210' }
];
addUser(user: User): Observable<User> {
user.id = this.users.length + 1;
this.users.push(user);
console.log("User Object-");
console.log(user);
console.log("Users List-");
console.log(this.users);
return of(user);
}
}
Component Code -
import { Component, OnInit } from '@angular/core';
import { NgForm } from '@angular/forms';
import { User } from '../models/user.model';
import { UserService } from '../service/user.service';
@Component({
selector: 'app-user-form',
templateUrl: './user-form.component.html',
styleUrls: ['./user-form.component.css'],
standalone: false
})
export class UserFormComponent implements OnInit {
users: User[] = [];
selectedUser: User = { id: 0, name: 'z', email: '', phone: '' };
constructor(private userService: UserService) { }
ngOnInit(): void {
}
onSubmit(form: NgForm): void {
if (form.valid) {
this.userService.addUser(this.selectedUser).subscribe(() => {
});
}
}
}
-
please share the component code alsoNaren Murali– Naren Murali2025年05月19日 13:07:47 +00:00Commented May 19 at 13:07
-
i have added component code. but data is getting passed to service correcltly as shown in console log in service.tsHeemanshu Bhalla– Heemanshu Bhalla2025年05月20日 04:06:06 +00:00Commented May 20 at 4:06
2 Answers 2
When you push data into the service array, clone it and push it. So that modifications to the user object do not affect the service object.
Remember objects are arrays are stored as memory references in javascript, so when you modify it (inside the component), all locations using this reference are updated (inside the service).
addUser(user: User): Observable<User> {
// const clonedUser = structuredClone(user);
const clonedUser = JSON.parse(JSON.stringify(user));
clonedUser.id = this.users.length + 1;
this.users.push(clonedUser);
console.log("User Object-");
console.log(clonedUser);
console.log("Users List-");
console.log(this.users);
return of(clonedUser);
}
3 Comments
//In component
console.log('User before passing to service', user); this.userService.addUser(user);
//in service give with below spread operator check once keep the debugger verify at what point it cuasing the issue.
const newUser = { ...user, id: this.users.length + 1 }; this.users.push(newUser);