How to read data from BehaviourSubject and emit new data into it

518 views Asked by At

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

https://stackblitz.com/edit/angular-buwj6n

1

There are 1 answers

2
sys__admin On BEST ANSWER

I am not sure if I got your question correctly...

But have you tried to use Subject.value?

 export class AppComponent implements OnInit {
 response;

 $subject: BehaviorSubject<any[]> = new BehaviorSubject<any[]>([]);

 constructor(private http: HttpClient) {
  this.$subject.subscribe(res => console.log(res));
 }

 ngOnInit(): void {
   this.http.get<{data: []}> ('http://dummy.restapiexample.com/api/v1/employees')
    .subscribe(res => this.$subject.next(res.data));
 }

 onSubmit() {
  this.$subject.value.push(
   {id: 25, employee_name: 'Sys', employee_salary: 85600, employee_age: 23, profile_image: ''}
  );
  this.$subject.next(this.$subject.value);
 }
}