从共享服务调用组件的方法

时间:2017-05-26 10:08:02

标签: angular angular-material

我想从我的共享服务中调用sidenav组件的方法open()。如果我直接从组件调用方法,它工作正常。但是当我从共享服务调用相同的方法时,我收到了一条错误消息:

  

错误类型错误:无法读取未定义

的属性“打开”

Sidenav组件:

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

@Component({
  selector: 'app-sidebar-content',
  template: `
   <md-sidenav-container class="container">
     <md-sidenav #sidenav class="sidenav">
       Jolly good!
     </md-sidenav>

     <app-main-content></app-main-content>

   </md-sidenav-container>
  `,
  styleUrls: ['./sidebar-content.component.css']
})
export class SidebarContentComponent implements OnInit {

  @ViewChild('sidenav') el: MdSidenav;

  constructor() { }

  ngOnInit() {

  }

  openSideNav() {
    this.el.open();    
  }

}

共享服务:

import { SidebarContentComponent } from './../content/sidebar-content/sidebar-content.component';
import { Injectable } from '@angular/core';


@Injectable()
export class SharedService {

  constructor(private sc: SidebarContentComponent) { }

  openSidenav() {
    this.sc.openSideNav();
  }

}

从其他组件调用open方法:

import { SharedService } from './../../services/shared.service';
import { Component, OnInit } from '@angular/core';

import { SidebarContentComponent } from './../sidebar-content/sidebar-content.component';

@Component({
  selector: 'app-main-content',
  templateUrl: `
   <div class="sidenav-content">
       <app-toolbar></app-toolbar>
       <button md-button (click)="open()">
         Open sidenav
       </button>
       <button md-button (click)="openWithService()">
         Open sidenav with service
       </button>
   </div>
  `,
  styleUrls: ['./main-content.component.css']
})
export class MainContentComponent implements OnInit {

  constructor(private sc: SidebarContentComponent, private ss: SharedService) { }

  ngOnInit() {
  }

  open() {
    this.sc.openSideNav();
   // Works fine
  }

  openWithService() {
    this.ss.openSidenav();
  // Throws an error
  // ERROR TypeError: Cannot read property 'open' of undefined
  }

}

1 个答案:

答案 0 :(得分:2)

您没有设置服务的SidebarContentComponent。即使你能做到,我认为正确的方法是使用rxjs / Subject。

这应该这样做:

SharedService

import { Subject } from 'rxjs/Subject'; // don't forget to import it!

public open$: Subject<any> = new Subject();

SidenavComponent

this.sharedService.open$.subscribe(() => this.openSideNav());

AnyComponent

this.sharedService.open$.next();