我正在使用服务来集中我的逻辑代码,但是当我的服务中的属性_opened
发生变化时,我找不到如何通知我的其他组件的方法。
app.service.ts
import { Injectable} from '@angular/core';
export class AsideService{
_opened: boolean = true;
_toggleSidebar() {
this._opened = !this._opened;
return this._opened;
}
}
dashboard.component.html
<p (click)="_toggleSidebar()">
<span></span>
<span></span>
<span></span>
dashboard.component.ts
import { Component, OnInit } from '@angular/core';
import { AsideService } from '../aside.service';
@Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {
open: any;
constructor(private asideService: AsideService) {
this.open = this.asideService._toggleSidebar();
}
ngOnInit() {
}
}
答案 0 :(得分:1)
有几种方法可以做到这一点。最明显的原因是将包含_opened
变量的对象传递给组件。然后你会得到以下内容:
import { Injectable} from '@angular/core';
export class AsideService{
_state: Object = {
_opened: true
};
_toggleSidebar() {
this._state._opened = !this._state._opened;
return this._state;
}
_getState(){
return this._state;
}
}
在您的组件中,您需要从服务中检查_state._opened
的值。这是因为您无法在组件之间传递原始值 - 您需要将它们包围在对象中。然后,例如在你的组件中,你可以去:
export class DashboardComponent实现OnInit { serviceState:any; 构造函数(private asideService:AsideService){ this.serviceState = this.asideService._toggleSidebar(); } }
并在您的组件中HTML:
<div>{{serviceState._opened}}</div>
这将显示您服务中_opened
的价值。
另一种方式涉及事件,但我不建议这样做。