我希望警报显示在我的静态引导程序v4导航栏内/上方。
所以我得到了这个简单的服务:
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
@Injectable()
export class AppService {
private _navbarPadding: number = 50;
navbarPaddingChange: Subject<number> = new Subject();
constructor() {
this.navbarPadding = this._navbarPadding;
}
get navbarPadding(): number {
return this._navbarPadding;
}
set navbarPadding(val: number) {
this._navbarPadding = val;
this.navbarPaddingChange.next(this._navbarPadding);
}
}
我随处注入,包括侧栏(下方)和'主体':
import { Component, OnInit, OnDestroy } from '@angular/core';
import { AppService } from '../app.service';
import { Subscription } from 'rxjs';
@Component({
selector: 'app-sidebar',
templateUrl: './sidebar.component.html',
styleUrls: ['./sidebar.component.css']
})
export class SidebarComponent implements OnInit, OnDestroy {
navbarPadding: number;
subNavbarPadding: Subscription;
constructor(public appService: AppService) {}
ngOnInit() {
this.navbarPadding = this.appService.navbarPadding;
this.subNavbarPadding = this.appService.navbarPaddingChange.subscribe(val =>
this.navbarPadding = val
);
}
ngOnDestroy() {
this.subNavbarPadding.unsubscribe();
}
}
然后我有了这个功能:
addAlert() {
this.appService.navbarPadding += 81;
this.alertsService.alerts.push({
type: 'info',
msg: 'INFO'
})
}
补充工具栏html(第一行):
<div class="col-sm-3 col-md-2 sidebar" [style.margin-top.px]=navbarPadding>
......它运作得很好。但是......这一定是个糟糕的主意。它到处都有很强的耦合。什么是正确的Angular2方法?
答案 0 :(得分:1)
一般来说,这是一种有效的方法,但是,我建议尽可能简化控制器,并在使用async
时使用Observables
- 管道:
您的服务(使用BehaviorSubject
而不是Subject
,虽然吸气剂和设定器可能也可以,但addAlert
中您可以使用this.appService.navbarPadding$.next(131)
):
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
@Injectable()
export class AppService {
private _navbarPadding: number = 50;
navbarPadding$: BehaviorSubject<number> = new BehaviorSubject(this._navbarPadding);
constructor() {
}
get navbarPadding(): number {
return this._navbarPadding;
}
set navbarPadding(val: number) {
this._navbarPadding = val;
this.navbarPadding$.next(this._navbarPadding);
}
}
组件保持最低限度(无手动订阅):
import { Component, OnInit, OnDestroy } from '@angular/core';
import { AppService } from '../app.service';
import { Subscription } from 'rxjs';
@Component({
selector: 'app-sidebar',
templateUrl: './sidebar.component.html',
styleUrls: ['./sidebar.component.css']
})
export class SidebarComponent implements OnInit, OnDestroy {
constructor(public appService: AppService) {}
}
您的模板(async-pipe自动处理订阅):
<div class="col-sm-3 col-md-2 sidebar" [style.margin-top.px]="appService.navbarPadding$ | async">
由于您的方法类似于ngrx,因此您可能需要查看ngrx-store,它为您提供了一种非常好的方法来处理这些类型的应用程序状态,例如填充。< / p>