1

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(() => {
 });
 }
 }
}

enter image description here

porgo
1,7513 gold badges19 silver badges30 bronze badges
asked May 19 at 12:57
2
  • please share the component code also Commented 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.ts Commented May 20 at 4:06

2 Answers 2

0

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);
 }
 
answered May 19 at 13:11
Sign up to request clarification or add additional context in comments.

3 Comments

'user' parameter of adduser funciton already has data why we need to stringify and parse it to push to list of array
@HeemanshuBhalla to create a new memory reference when it is pushed to the service, else, the manipulations we make the the user at the component level, will affect the service addition also, because arrays and objects are stored as memory references, so cloning creates a new memory reference
okay, I need to check this bcoz everywhere i checked they didn't used this approch i mean if parameter type is same as object we are inserting then it should push. let me check about the approch like sometime object we pass are complex if we need to reclone them its a tought task
0

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

answered May 19 at 14:21

1 Comment

as we are already passing data to service function parameter then why we need to reassign it using a const

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.