Rxjs Subject 不立即发射数据

Rxjs Subject not emitting data immediately

我有一个 RXJS 主题的服务,我正在将数据分配给内部构造函数中的主题,执行 api 调用。我在组件模板中订阅了这个主题。虽然数据已提供给主题,但第一次并没有立即发出。

interface Employee {
employee_age: number;
employee_name: string;
employee_salary: number;
id: string;
profile_image: string;
}

@Injectable({
  providedIn: "root",
})
export class EmployeeService {
 employeesSub = new Subject<Employee[]>();

 employees: Employee[];

 constructor(private http: HttpClient) {

this.api().subscribe((res) => {
  this.employees = res.data;
  this.employeesSub.next(this.employees);
});

}

 getEmployees(){
     this.employeesSub.next(this.employees);
 }

 addEmployee(name,age,salary) {
    this.employees.unshift({id:(this.employees.length + 
 1).toString(),employee_age:age,employee_name:name,employee_salary:salary,profile_image:""});
   this.employeesSub.next(this.employees);
 }
 
 api() {
    return this.http
     .get<any>(environment.employeeUrl)
     .pipe(map((data) => data.items));
   }
  }

 Code in template

  <h2>List</h2>
  <div style="display: flex;"></div>
  <table>
     <tr *ngFor="let item of employeeService.employeesSub|async">
       <td>      {{ item.employee_name}}    </td>
       <td>      {{ item.employee_age}}    </td>
       <td>      {{ item.employee_salary}}    </td>
     </tr>
  </table>

我正在通过在 200 毫秒后调用 getEmployees() 函数重新分配数据并且它正在工作。知道为什么会这样。

您需要切换到 BehaviorSubject

服务在组件之前初始化,因此它在组件订阅之前发出值。由于 Subject 不包含任何值,因此组件不会得到任何东西。通过切换到一个 Behavior 主题,您可以订阅它并立即获取最新值。

此处接受的答案好吧。

// Init the subject with a starting value, to be updated in the constructor later
employeesSub = new BehaviorSubject<Employee[]>([]);

constructor(private http: HttpClient) {
    this.api().subscribe((res) => {
        this.employees = res.data;
        this.employeesSub.next(this.employees);
    });
}