我创建了一项服务,以便从API中获取数据并使用主题从我的组件中获取这些数据(在应用程序初始化时调用LoadTenants):
服务:
@Injectable()
export class TenantService{
public tenants;
private tenantSubject = new Subject<any>();
constructor(private http: HttpClient) {
}
LoadTenants() {
this.http.get(TENANT_URL).subscribe((data: any) => {
this.tenants = data;
this.setTenants();
});
}
setTenants() {
this.tenantSubject.next(this.tenants);
}
getTenants(): Observable<any> {
return this.tenantSubject.asObservable();
}
getSyncTenants() {
return this.tenants;
}
}
组件:
public tenant;
subsciption: Subscription;
constructor(private tenantService: TenantService) { }
ngOnInit() {
this.subsciption = this.tenantService.getTenants().subscribe((datas) => {
this.tenant = datas;
},
error => console.log('Error : ', error)
);
}
}
ngOnDestroy() {
this.subsciption.unsubscribe();
}
在第一次加载时一切运行正常,但是如果我导航到另一个组件并返回到该组件,则不会触发订阅,导致模板中的无效数据。
答案 0 :(得分:4)
如果要获取最新值,请使用BehaviorSubject
BehaviorSubject将直接向订阅者发送当前值
@Injectable()
export class TenantService{
public tenants;
private tenantSubject = new BehaviorSubject<any>();
constructor(private http: HttpClient) {
}
LoadTenants() {
this.http.get(TENANT_URL).subscribe((data: any) => {
this.tenants = data;
this.setTenants();
});
}
setTenants() {
this.tenantSubject.next(this.tenants);
}
getTenants(): Observable<any> {
return this.tenantSubject.asObservable();
}
getSyncTenants() {
return this.tenants;
}
}