我试图在一个组件中设置一个值,如果在另一个组件中触发了一个函数。
但是,我无法让它发挥作用。
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
中的值订阅了emit事件,所以如果不是这样,它应该在更新后立即更新,如果不是的话?
感谢您的帮助:)
答案 0 :(得分:4)
您提供了两个服务实例,ComponentInteractionService必须只在一个提供程序中(例如AppComponent中的例子)