【问题标题】:How to read data from BehaviourSubject and emit new data into it如何从 BehaviourSubject 读取数据并将新数据发送到其中
【发布时间】: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 上找到

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

【问题讨论】:

标签: angular rxjs rxjs-observables rxjs-pipeable-operators


【解决方案1】:

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

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

【讨论】:

  • 如果我在订阅中重新发送新数据,这将成为一个无休止的发送和订阅过程
  • 谢谢@sys__admin。我不知道 BehaviorSubject 有一个 value 属性可以在不订阅的情况下获取数据
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-01
  • 1970-01-01
  • 2020-09-22
  • 1970-01-01
  • 2012-08-16
相关资源
最近更新 更多