将功能传递给路由器插座组件

时间:2016-09-22 15:51:58

标签: angular

我有两个我在服务中定义的函数,我在nav组件中调用该服务。但是我仍然收到此错误EXCEPTION: Error in app/html/nav.html:5:48 caused by: Cannot read property 'hoverIn' of undefinedErrorHandler.handleError

showhide.service

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

@Injectable()
  export class ShowHideService {

   public hoverIn(){
       document.getElementById('title').style.display = 'block';
   };
   public hoverOut(){
       document.getElementById('title').style.display = 'none';
   };

}

nav.component

import {Component} from '@angular/core';
import { ShowHideService } from '../services/showhide.service';

@Component({
   selector: 'nav',
   templateUrl:'./app/html/nav.html',
   styleUrls: ['./app/Css/nav.css'],
})
export class NavComponent {
   constructor(private _showhide: ShowHideService) {

       this._showhide.hoverIn();
       this._showhide.hoverOut();
   }
}

nav.html

 <div class="header">
        <p #title class="title">Title</p>
        <div>
            <ul class="nav">
                <li class="navItem">
                    <a class="navlinks"  routerLink="/gtm (mouseover)="_showhide.hoverIn()" 
                    (mouseout)="_showhide.hoverOut()">Nav Item</a></li>
                <li class="navItem"><a class="navlinks" routerLink="/">Home</a></li>
            </ul>
        </div>
    </div>

提前致谢如果有任何问题或要求提供更多信息,我会根据需要进行编辑。

1 个答案:

答案 0 :(得分:2)

这是共享服务的完美用例。

您可以将此服务注入所需的每个组件并使用服务功能。

请参阅此plunker:https://plnkr.co/edit/8QTmKJazNSC03saBVy2q?p=catalogue

import {Component, NgModule, Injectable} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'

@Injectable()
export class MyService {

  public anyFunction() { console.log('!') }

}

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2 (mouseover)="_service.anyFunction()" (mouseout)="_service.anyFunction()" >Hello {{name}}</h2>
    </div>
  `,
})
export class App {
  name:string;
  constructor(private _service: MyService) {
    this.name = 'Angular2'

    // now you can use the service in this component..
    this._service.anyFunction();
  }

}

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App ],
  providers: [ MyService ],
  bootstrap: [ App ]
})
export class AppModule {}