I have a BehaviourSubject with an array of employee data. When I want to add a new employee to the array, I want to take old data, insert new records into it, and reemit that into the behaviour subject. I am not able to get a clue on how to do that.
export class EmployeeService {
employeesSub = new BehaviorSubject<Employee[]>([]);
constructor(private http: HttpClient) {
this.api().subscribe((res) => {
this.employeesSub.next(res.data);
});
}
addEmployee(name,age,salary) {
this.employeesSub.pipe(
map((res:Employee[])=>{
res.unshift({id:(res.length + 1).toString(),employee_age:age,employee_name:name,employee_salary:salary,profile_image:""});
return res;
})
).subscribe(emp=>{
// this.employeesSub.next(emp);
})
}
api() {
return this.http
.get<any>("http://dummy.restapiexample.com/api/v1/employees")
.pipe(map((data) => data.items));
}
}
I am trying something similar to add employee method but able to fix it.
The same code can also be found at StackBlitz
I am not sure if I got your question correctly...
But have you tried to use Subject.value?