【问题标题】:Component interaction via service not working in Angular2通过服务进行的组件交互在 Angular2 中不起作用
【发布时间】:2017-01-08 02:10:33
【问题描述】:


如果在另一个组件中触发了某个功能,我正在尝试在一个组件中设置一个值。 但是,我无法让它工作。 I am using the approach given in this post

我希望我的侧边栏仅在按下登录按钮后显示。

我写了一个这样的服务组件:
component-interaction.service.ts

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

@Injectable()
export class ComponentInteractionService {

        showSidebarEmitter: EventEmitter<any> = new EventEmitter();

        setSidebar(showSidebar:boolean){
            this.showSidebarEmitter.emit(showSidebar);
        }

}

然后我在我的sidebar.component.ts 中订阅可以接收新值的组件:

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { ComponentInteractionService } from '../services/component-interaction.service';

@Component({
  moduleId: module.id,
  selector: 'app-sidebar',
  templateUrl: 'sidebar.component.html',

  styleUrls: ['sidebar.component.css'],
   providers: [ ComponentInteractionService ]
})

export class SidebarComponent implements OnInit {
  showSidebar: boolean = false;

  constructor(private _router: Router,  private _componentInteractionService: ComponentInteractionService) { }

  ngOnInit() {
      this._componentInteractionService.showSidebarEmitter.subscribe(res =>this.showSidebar = res);

  }

}

我正在我的login.component.ts 中设置值,如下所示:

import { Component, OnInit, EventEmitter, Output } from '@angular/core';
import { Observable } from 'rxjs/Rx'; 
import { ComponentInteractionService } from '../services/component-interaction.service';

@Component({  
  moduleId: module.id,
  selector: 'app-login',
  templateUrl: 'login.component.html',
  styleUrls: ['login.component.css'],
  providers: [ ComponentInteractionService ]
})
export class LoginComponent implements OnInit {

  login(){
   this._componentInteractionService.setSidebar(true);
  }
}

现在,由于我的 sidebar.component.ts 中的值订阅了发出事件,它应该在更改后立即更新,不是吗?

感谢您的帮助:)

【问题讨论】:

    标签: angular angular-services


    【解决方案1】:

    您已经提供了两个服务实例,ComponentInteractionService 必须只在一个提供者中(例如在 AppComponent 中)

    【讨论】:

    • 如果我不清楚:从组件装饰器中的“providers”标签中删除 ComponentInteractionService,将其保留在构造函数中,然后将 ComponentInteractionService 放在 AppComponent 的 providers 标签中(或根组件的其他名称)
    • 太棒了,它正在工作。感谢您的快速回答!
    • 我不知道你是否有意使用以前的 RC5 Angular2 版本,但如果你不这样做,你可能还应该从装饰器中删除提供者的东西并将其放入 @module
    • 所以基本上我把所有的提供者都放在了我的 app.module.ts 文件中,然后从所有其他的文件中删除它们?我开始的时候它还在 RC4 上,但试图全部更新到 RC5
    • 您可以将提供程序放在任何模块中,您只需要注意两件事:服务必须仅在一个模块中(共享模块可能很棘手),如果延迟加载可能会产生问题模块尚未加载
    猜你喜欢
    • 2016-07-19
    • 1970-01-01
    • 2017-06-16
    • 2017-03-08
    • 2020-01-11
    • 2017-07-20
    • 2017-12-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多