Angular,RxJS:为具有AsyncSubject源的Observable分配一个新值



我需要创建一个包含服务从服务器获取的设置的服务。这些设置在应用程序中广泛使用,而不仅仅是在一个地方:

@Injectable()
export class SettingsService {
private apiResource = '/settings';
private settingsSubject$: AsyncSubject<Settings> = new AsyncSubject();
public settings$: Observable<Settings> = this.settingsSubject$.asObservable();
constructor(private jsonApiService: JsonApiService) {
}
public init(): void {
this.get()
.subscribe(settings => {
this.settingsSubject$.next(settings);
this.settingsSubject$.complete();
});
}
public update(settings: Settings) {
return this.jsonApiService.post(`${this.apiResource}`, settings)          
}
private get() {
return this.jsonApiService.get(`${this.apiResource}`);
}
}

我把加载数据放在init方法中,并从CoreModule调用它,以便在应用程序启动时获得数据:

export class CoreModule {
constructor(private settingsService: SettingsService) {
this.settingsService.init();
}

正如您所看到的,我使用AsyncSubject来强制所有订阅者等待请求何时完成。

问题是当调用update函数时,如何分配新值?我尝试使用:

public update(settings: Settings) {
return this.jsonApiService.post(`${this.apiResource}`, settings)   
.do(() => {
this.settings$ = Observable.of(settings);
});       
}

但什么也没发生。而且,我认为这不是一个正确的方法。

PS。一个使用示例:

export class SettingsComponent implements OnInit {
public settings: Settings;
public settingsForm: FormGroup;
constructor(private settingsService: SettingsService,
private fb: FormBuilder) {
}
ngOnInit() {
this.settingsService.settings$
.subscribe(data => {
this.settings = data;
this.settingsForm = this.fb.group({
corValue: [this.settings.corValue],
});
});
}
}
<div *ngIf="settings">
<form [formGroup]="settingsForm">
...
</form>
</div>

另一种用法是服务:

@Injectable()
export class CalculationService {
private corValue: number;
constructor(private settingsService: SettingsService) {
this.settingsService.settings$
.subscribe(settings => {
this.corValue = settings.corValue;
})
}
... different functions that make some math calculations and some functions use corValue.  
}

PS2.我不能使用APP_INITIALIZER,因为我的设置是特定于用户的,所以用户必须首先登录。

如果我理解正确,您希望将值发送到settingsSubject$,以便您在settings$上的订户在下游接收它们:

public update(settings: Settings) {
return this.jsonApiService.post(`${this.apiResource}`, settings)   
.do(() => {
this.settingsSubject$.next(settings);
});       
}

最新更新