Angular 2 Service更新时更新UI

时间:2016-12-01 17:32:39

标签: angular angular2-template

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

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

1 个答案:

答案 0 :(得分:1)

永远不要深度导入Angular模块。此外,您导入的模块不再存在:

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

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

问题在于角度如何通过变化检测进行。视图应仅从以下位置更新:

  1. 本身
  2. 输入属性
  3. 一个可观察的
  4. 这是为了保证单次传递足以处理视图。

    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) {
        }
    }