Angular2使用服务来维护状态

时间:2016-09-30 22:13:00

标签: angular

我正在尝试创建一个保存当前路由状态的服务。我无法弄清楚如何做到这一点,因为我认为我当前的实现会起作用:

app.module.ts

@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    BrowserModule,
    PagesModule,
    UIModule,
    routing
  ],
  providers: [HelpersService],
  bootstrap: [AppComponent]
})
export class AppModule { }

helpers.service.ts

@Injectable()
export class HelpersService {
  activePage = '';
  constructor() {}

  setActivePage(name) {
    this.activePage = name;
  }

  getActivePage() {
    return this.activePage;
  }

}

dashboard.component.ts(PagesModule的一部分)

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.scss']
})
export class DashboardComponent implements OnInit {

  constructor(private _activeRoute: ActivatedRoute,
              private _helpersService: HelpersService) { }

  ngOnInit() {

    this._activeRoute.data.subscribe(
      value => {
        this._helpersService.setActivePage(value); 
      }
    );

  }

}

top-bar.component.ts(UIModule的一部分)

@Component({
  selector: 'app-top-bar',
  templateUrl: './top-bar.component.html',
  styleUrls: ['./top-bar.component.scss']
})
export class TopBarComponent implements OnInit {
  // holds the active page
  activePage:string;

  constructor(private _helpersService: HelpersService) { 

  }

  ngOnInit() {
    this.activePage = this._helpersService.getActivePage();
  }

}

这总是返回undefined。

0 个答案:

没有答案