使用更改检测策略作为 OnPush 从服务强制更改检测

Force change detection from service with Change detection strategy as OnPush

我们的 Angular2 应用程序正在使用翻译服务来提供翻译,就像这样

getResourceValue(resKey: string): string {
  return this.translateService.getResourceValue(resKey);
}

服务从加载每个组件的 API 调用中获取翻译异步。一个 observable 持有所有的翻译异步。如果该密钥的翻译还没有准备好,它只是 returns 密钥。然后在翻译准备就绪时用正确的字符串更新它。

在模板中:

getResourceValue('Page-Title')

效果很好。

但是有些页面有"ChangeDetectionStrategy.OnPush"。当翻译数据发生变化时,这些页面不会触发变化检测。没有该设置一切正常。

我的问题是:有没有办法强制检测某个地方只为翻译?

感谢 angular2localization,通过像这样传递 ChangeDetectorRef 解决了这个问题:

在服务中,我们有一个函数来加载传入的 Json 文件和一个 ChangeDetectorRef 对象:

getTranslation(resPath: string, changeDetector?: ChangeDetectorRef): Observable<any> {
    return Observable.of(this.processTranslation(resPath, changeDetector));
    }
}

翻译完成后,changeDetector 将调用 markForCheck 方法;

在每个需要翻译的组件中,我们都会调用这个函数,传入这个组件的changeDetector。

很好的解决了这个问题。

希望这可以帮助到一些人。