I have component structure like this
- Parent Component (card-list)
- Child (Card)
- Child (detail-card)
- Child (Form)
- service
I try to push data from FormComponent to service and it works, but if I switch to another page(CardList Component). I can't get the same data from the service, just my default array, and can't find the data that was previously pushed. I don't know why it happens, I need some help My code like this
formComponent
export class FormComponent implements OnInit {
constructor(
private accountService: AccountsService,
private fb:FormBuilder,
userForm: FormGroup;
ngOnInit(){
this.userForm = new FormGroup({
'id': new FormControl(null, Validators.required),
'name': new FormControl(null, Validators.required),
})
})
}
onCreateAccount() {
this.accountService.account(this.userForm.value);
console.log(this.userForm);
console.log(this.accountService.accounts);
}
AccountsService
export class AccountsService {
accounts = [
{
id: 1234556,
name: 'Jhon ',
},
];
account(userData){
if (userData){
this.accounts.push(userData)
}
}
getDataId(id: number) {
return this.accounts.find(acc => acc.id == id)
}
card-list
import { Component, OnInit } from '@angular/core';
import { AccountsService } from '../account.service';
@Component({
selector: 'app-card-list',
templateUrl: './card-list.component.html',
styleUrls: ['./card-list.component.css'],
providers: [AccountsService]
})
export class CardListComponent implements OnInit {
accounts: {id:number, }[] = [];
constructor(private accountsService: AccountsService) {}
ngOnInit() {
this.accounts = this.accountsService.accounts;
console.log(this.accounts)
}
CodePudding user response:
service is a Singleton, but in your CardListComponent you set providers: [AccountsService]
what's means you created another instance of this service, so this instance is not update with the new data...
just remove this line and make sure AccountService is provide only once.
the default of angular
@Injectable({ providedIn: 'root' }) above the the line export class AccountService
