尝试创建一个“设置”组件,该组件可全局用于配置var

时间:2019-02-27 16:01:49

标签: angular angular-material

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

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

中找到

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

谢谢。...

1 个答案:

答案 0 :(得分:0)

要使您的服务在Angular应用程序中全局可用,请在您的服务元数据中添加providedIn: 'root'

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

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

@NgModule({
  providers: [AppSettingsService ]
  ...
})
export class AppModule {}