尝试创建一个可以全局用于配置变量的“设置”组件

问题描述 投票:0回答:1

我正在尝试为我的应用程序创建一个“设置”组件,用于存储全局配置设置。我有一个组件,它是对它们进行更改工作的容器,我已经能够创建一组默认值,现在我正在尝试使用一个服务来初始化它们,这些服务将被调用以填充运行时设置对象。我想在这里应该如何做到这一点上缺少一些基金会。当我尝试初始化服务中的对象时,我得到一些错误,我不知道该怎么做。这是服务代码:

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import { AppSettings } from '../shared/app-settings';
import { APPSETTINGS } from "../shared/defaultSettings";

@Injectable()
export class AppSettingsService {
  getSettings(): Observable<AppSettings> {
    let settings =  APPSETTINGS;
    return Observable.of<AppSettings>(settings);
  }
}

这是我尝试在settings-container组件中使用它们的地方:

export class SettingsContainerComponent implements OnInit {

  @Input()
  defaultSettings: APPSETTINGS;

  themes = [
    { value: 'DEFAULT-THEME', label: 'blue' },
    { value: 'LIGHT-THEME', label: 'light' },
    { value: 'NATURE-THEME', label: 'nature' },
    { value: 'BLACK-THEME', label: 'dark' }
  ];

  @Input()
  title: string;

  constructor(private appSettingsService: AppSettingsService) { }

  ngOnInit() {  
    console.log('settings title, ', this.title);
    console.log('settings: ', this.defaultSettings)
    //this.appSettingsService.getSettings()
      //.subscribe(console.log(defaultSettings),
        //() => null,
        //() => {
          //console.log('settings: ', this.settings);
        //});
    console.log('settings, stickyHeader: ', this.settings.stickyHeader);  
  }

即使我已经注释掉订阅代码,我仍然会收到以下运行时错误:

vendor.js:76623 ERROR Error: Uncaught (in promise): Error:     StaticInjectorError(AppModule)[SettingsContainerComponent -> AppSettingsService]: 
  StaticInjectorError(Platform: core)[SettingsContainerComponent ->     AppSettingsService]: 
    NullInjectorError: No provider for AppSettingsService!
Error: StaticInjectorError(AppModule)[SettingsContainerComponent ->     AppSettingsService]: 
  StaticInjectorError(Platform: core)[SettingsContainerComponent ->     AppSettingsService]: 
    NullInjectorError: No provider for AppSettingsService!
    at     NullInjector.push../node_modules/@angular/core/fesm5/core.js.NullInjector.get     (vendor.js:69804)

整个项目可以在https://github.com/cpeddie/TRACS3.git找到

有人能指出我这样做的正确方法吗?

谢谢....

angular angular-material
1个回答
0
投票

要在Angular应用程序中全局提供服务,请将providedIn: 'root'添加到服务元数据中:

@Injectable({
  providedIn: 'root'
})
export class AppSettingsService {
  ...
}

或者将此服务添加到AppModule的providers数组中:

@NgModule({
  providers: [AppSettingsService ]
  ...
})
export class AppModule {}
© www.soinside.com 2019 - 2024. All rights reserved.