订阅主题只触发一次
Subscribe to a subject only fired once
我创建了一个服务以便从 API 获取数据并使用 Subject 从我的组件获取这些数据(在应用程序初始化时调用 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();
}
第一次加载时一切正常,但如果我导航到另一个组件并返回到这个组件,则不会触发订阅,导致我的模板中出现无效数据。
如果你想获得最新值,那么使用 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;
}
}
我创建了一个服务以便从 API 获取数据并使用 Subject 从我的组件获取这些数据(在应用程序初始化时调用 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();
}
第一次加载时一切正常,但如果我导航到另一个组件并返回到这个组件,则不会触发订阅,导致我的模板中出现无效数据。
如果你想获得最新值,那么使用 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;
}
}