订阅observable不能正确执行

时间:2016-08-19 18:55:45

标签: angular

更新 我能够通过关注Cory Rylan撰写的博客文章来解决我的可观察问题Blog Post

我正在尝试订阅一个类型为Theme的可观察对象。当主题发生变化时,我需要通知app.component有关更改。

所以我在themes.service中有这个:

setTheme(theme: string) {
    var ft = this.findTheme(this.selectedTheme);
    this.selectedTheme = theme;
    var d = document.getElementById('themeStyleSheet')
    d.setAttribute('href', this.getThemePath(theme));
    this.setNewTheme(ft);
}

setNewTheme(theme: Theme): void {
    console.log("setting new theme");
    this.theme = theme;
    this.subject.next(theme);
}

getNewTheme(): Observable<Theme> {
    return this.subject.asObservable();
}

在我的app.component中:

export class AppComponent implements OnInit {
    private items: MenuItem[];
    appPageHeaderDivStyle: {};
    selectedTheme: Theme;
    errorMessage: string;
    //loggedIn: LoggedIn;

    constructor(
        private appMenuService: AppMenuService,
         private themeService: ThemeService)
        // private loginService: LoginService)
         { 
    }
ngOnInit() {

  console.log('going to get new theme');
  this.themeService.getNewTheme()
    .subscribe(
    theme => this.selectedTheme = theme,
    error => {
      this.errorMessage = error
      debugger;
    },
    () => this.completeGetNewTheme()
  );

  this.themeService.setTheme("Pepper-Grinder");
  this.items = this.appMenuService.getNoLoginMenu();
}

completeGetNewTheme() {
  console.log("in complete new theme");
  this.appPageHeaderDivStyle = this.themeService.getAppPageHeaderDivStyle();
}

主题服务注入了shared.module中的声明:

@NgModule({
  imports:      [ CommonModule, RouterModule ],
  declarations: [Menubar, Galleria, InputText, Panel, Button, Dropdown, Dialog], //, Checkbox, Calendar, RadioButton, SelectButton, DataTable, Column, Dropdown, Accordion, AccordionTab], //, ControlErrorMessagesComponent ],
  exports:      [ CommonModule, ReactiveFormsModule, HttpModule, RouterModule, Menubar, Galleria, InputText, Panel, Button, Dropdown, Dialog] //Menubar, Galleria, InputText, Checkbox, Panel, Calendar, RadioButton, SelectButton, DataTable, Column, Button, Dropdown, Accordion, AccordionTab ]
})

export class SharedModule {
//
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: SharedModule,
      providers: [SettingsService, AppMenuService, AuthorizationService, LoginService, RegisterService, ThemeService, ValidationService, NutritionixService]
    };
  }
}

我已经通过setNewTheme方法跟踪了它,但是,订阅永远不会激活。我做错了什么?

0 个答案:

没有答案