Angular 如何从行为主体读取数据并向其中发送新数据

Angular 如何从行为主体读取数据并向其中发送新数据,angular,rxjs,rxjs-observables,rxjs-pipeable-operators,Angular,Rxjs,Rxjs Observables,Rxjs Pipeable Operators,我有一个行为主题,包含一系列员工数据。当我想向数组中添加新员工时,我想获取旧数据,在其中插入新记录,然后将其重新提交到行为主题中。我不知道该怎么做 export class EmployeeService { employeesSub = new BehaviorSubject<Employee[]>([]); constructor(private http: HttpClient) { this.api().subscribe((res) => {

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

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));
  }
}
导出类员工服务{
employeesSub=新行为主体([]);
构造函数(专用http:HttpClient){
this.api().subscribe((res)=>{
本.员工问题下一步(资源数据);
});
}
新增员工(姓名、年龄、工资){
这是我的雇员们的水管(
地图((res:Employee[])=>{
res.unshift({id:(res.length+1).toString(),employee_age:age,employee_name:name,employee_salary:salary,profile_image:“”);
返回res;
})
).订阅(emp=>{
//本.雇员委员会下一届会议(emp);
})
}
api(){
返回此文件。http

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

但是你试过使用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);
 }
}
导出类AppComponent实现OnInit{
反应;
$subject:BehaviorSubject=新的BehaviorSubject([]);
构造函数(专用http:HttpClient){
这个.subject.subscribe(res=>console.log(res));
}
ngOnInit():void{
this.http.get('http://dummy.restapiexample.com/api/v1/employees')
.subscribe(res=>this.$subject.next(res.data));
}
onSubmit(){
此.$subject.value.push(
{id:25,员工姓名:'Sys',员工工资:85600,员工年龄:23,个人资料图片:'}
);
this.$subject.next(this.$subject.value);
}
}

如果我在订阅中重新提交新数据,它将成为一个无休止的发送和订阅过程谢谢@sys\u admin。我不知道BehaviorSubject有一个value属性,可以在不订阅的情况下获取数据。通常的方法是。类似于
。next([…existingArray,newOne])
。在subscribe调用中调用next不起作用,因为您发现它会导致无限循环。