Angular 2 - 注入单个服务实例的最简单方法

时间:2016-09-28 23:55:23

标签: angular

在angular 2.0.0中,我有一个名为NavService的服务,它在多个组件之间共享。注入单个实例的单个实例在应用程序中的所有组件之间共享的最简单方法是什么?

目前我已经完成了我在app.module.ts文件中包含该服务的地方,但在我的Dashboard组件中尝试访问时,出现错误找不到名称'NavService'

app.module.ts

// Core
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { routing } from './app.routing';

// Shared Components
import { AppComponent } from './app.component';
import { NavBarComponent } from './nav/nav-bar/nav-bar.component';
import { DashboardComponent } from './dashboard/dashboard.component';
import { LayoutDirective, FlexDirective } from './layout.directive';
import { NavToolComponent } from './nav/nav-tool/nav-tool.component';

// Shared Pipes
import { AppFilterPipe } from './app-filter.pipe';

// Shared Service
import { NavService } from './nav/shared/nav.service'


@NgModule({
  declarations: [
    AppComponent,
    NavBarComponent,
    DashboardComponent,
    LayoutDirective,
    FlexDirective,
    NavToolComponent,
    AppFilterPipe
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    routing
  ],
  providers: [NavService],
  bootstrap: [AppComponent]
})
export class AppModule { }

dashboard.component.ts

import { Component, OnInit } from '@angular/core';

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

  view: string = 'Dashboard';
  currenView: string = null;
  constructor(private NavService: NavService) { }

  ngOnInit() {
    // Update Current View in Nav Service
    // Send RXJS mesage to nav tool on Change
    this.NavService.updateCurrentView('Dashboard');
    this.view = this.NavService.getCurrentView();
    console.log(this.view);

  }

  testFn(): void {
    this.view = this.NavService.getCurrentView();
    console.log(this.view);
  }
}

0 个答案:

没有答案