【发布时间】:2020-10-02 05:08:17
【问题描述】:
我有一个包含员工数据数组的 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 上找到
【问题讨论】:
-
通常的方式是call next and create a new array that includes all the old values and the new one。像
.next([...existingArray, newOne])这样的东西。在您的 subscribe 调用中调用 next 是行不通的,因为您发现它会导致无限循环。
标签: angular rxjs rxjs-observables rxjs-pipeable-operators