2016-12-01 96 views
0

我正在开发一个Angular2应用程序,其中有一个ConfigurationService和一个组件,需要注册此服务的属性更改。Angular 2更新服务更新UI

import {Injectable} from "angular2/src/core/di/decorators"; 
@Injectable() 
export class ConfigurationService { 
    private config = { 
     showDeveloperOptions: false 
    } 

    constructor() {} 

    get isDeveloper() { 
     return this.config.showDeveloperOptions; 
    } 


    public setDeveloperOptions(developerOptions: boolean) { 
     this.config.showDeveloperOptions = developerOptions; 
     console.warn("Set DeveloperOptions to " + this.config.showDeveloperOptions); 
    } 
} 

我的视图组件:

@Component({ 
    selector: 'developer', 
    template: `<div [hidden]="config.isDeveloper">Not a Developer</div>`, 
    providers: [ConfigurationService], 
}) 

export class DeveloperComponent { 
    constructor(public config: ConfigurationService) { 
    } 
} 

不幸的是,当我触发ConfigurationService.setDeveloperOptions(true)从那里这项服务得到了注入另一个服务,它不更新视图。

我在做什么错?

非常感谢!

Seb

+0

您如何将价值观融入您的观点? –

+0

[hidden] =“config.isDeveloper”,config在组件构造函数中设置为公共可访问变量。 – Sebastian

+0

我可能是错的,但我看到配置作为私人成员,并没有在构造函数?我知道你正在访问那个getter,因为它会发生什么,如果你只是声明var为public并直接绑定它(不使用getter)? –

回答

1

从不深入导入Angular模块。此外,在导入模块不再有:

import {Injectable} from "@angular/core"; 

这只是标记为依赖注入的服务,但在这里不是问题。

问题是角度如何进行变化检测。视图应该只从被更新:

  1. 本身
  2. 输入属性
  3. 可观察到的

这是为了保证单程足以工序图。

import {Injectable} from "@angular/core"; 
import {BehaviorSubject} from "rxjs/BehaviorSubject"; 

@Injectable() 
export class ConfigurationService { 
    private config = new BehaviorSubject({ 
     showDeveloperOptions: false 
    }); 

    constructor() {} 

    get isDeveloper() { 
     return this.config.map(config => config.showDeveloperOptions); 
    } 

    public setDeveloperOptions(developerOptions: boolean) { 
     this.config.next({showDeveloperOptions: developerOptions}); 
     console.warn("Set DeveloperOptions to " + developerOptions); 
    } 
} 

然后您使用async管道打开该值。该视图将自行更新。

@Component({ 
    selector: 'developer', 
    template: `<div [hidden]="(config.isDeveloper | async)">Not a Developer</div>`, 
    providers: [ConfigurationService], 
}) 

export class DeveloperComponent { 
    constructor(public config: ConfigurationService) { 
    } 
} 
+0

谢谢安德烈,这看起来像一个非常聪明的解决方案,异步管道是我以前从未见过的东西! – Sebastian