如何从 BehaviourSubject 读取数据并将新数据发送到其中

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

我有一个包含员工数据数组的 BehaviourSubject。当我想向数组添加新员工时,我想获取旧数据,将新记录插入其中,然后将其重新发送到行为主题中。我不知道该怎么做。

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

我正在尝试类似于添加员工方法但能够修复它。

同样的代码也可以在 StackBlitz 找到

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

我不确定我是否正确回答了你的问题...

但是你试过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);
 }
}