问题描述
我有一个带有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>
我正在通过200ms之后调用getEmployees()函数来重新分配数据,并且该函数正在工作。知道为什么会这样。
解决方法
您需要切换到describes the difference been a Subject
and a BehaviorSubject
。
该服务在组件执行之前被初始化,因此它在组件被订阅之前发出值。由于主题不包含任何值,因此组件不会获得任何东西。通过交换为“行为”主题,您可以订阅该主题并立即获取最新值。
这里{{3}}的公认答案很好。
// 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);
});
}