更改未触发订阅

时间:2018-08-22 10:29:34

标签: javascript angular

这里有组件,从按钮中调用switchUnit()函数。

export class UnitComponent {

    unit: string;

    constructor(@Inject(IUnitServiceToken) private unitService: IUnitService) {
        unitService.currentUnit().subscribe( s => {
            this.unit = s;
            console.log("unit constructor")
        });
    }

    switchUnit() {
        this.unit !== 'metric' ? this.unitService.changeUnit('metric') : this.unitService.changeUnit('imperial');
    }
}

这是我的服务,它通过接口使用,但这不会引起任何问题。

export class UnitService implements IUnitService  {

    private configuration: Configuration;
    private unitCallback: Function;

    constructor(@Inject(IConfigurationServiceToken) private configService: IConfigurationService,
        @Inject(ILogServiceToken) private logger: ILogService) {

        const scope = new ConfigurationScope();
        scope.location = ConfigurationLocation.LocalStorage;
        scope.path = '/user/';
        scope.name = 'preferences';
        this.logger.debug('Loaded unit service');
        this.configService.current(scope).subscribe( c => {
            this.configuration = c;
        });
    }

    changeUnit(unitName: string): void {
        this.logger.debug('Changing unit');
        this.configuration.content.unit = unitName;
        this.configService.confirmChange(this.configuration).subscribe(
            s => location.reload()
        );
    }

    currentUnit(): Observable<string> {
        return Observable.of(this.configuration.content.unit);
    }
}

当前刷新触发将重新加载页面,this.unit将读取更新的值。我想删除刷新,并更新this.unit。

我同意这不是此组件中的问题,但是我还有其他组件需要使用正确的单位值。

0 个答案:

没有答案