将组件的状态交给服务来控制

This commit is contained in:
小海
2020-04-23 23:18:29 +08:00
parent 2bcca393e1
commit 6f9eb718ce
8 changed files with 100 additions and 33 deletions

View File

@@ -0,0 +1,16 @@
import { TestBed } from '@angular/core/testing';
import { ComponentStateService } from './component-state.service';
describe('CompentStateService', () => {
let service: ComponentStateService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(ComponentStateService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});

View File

@@ -0,0 +1,61 @@
import {Injectable} from '@angular/core';
import {filter} from 'rxjs/operators';
import {NavigationEnd, Router, RouterEvent} from '@angular/router';
import {Observable, of, Subscriber} from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class ComponentStateService {
constructor(private router: Router) {
this.watchRouterChange()
}
visible = {
header: true,
footer: true,
globalBackToTop: true
}
currentPath: string
getCurrentRouterPath = () => this.currentPath;
watchRouterChange() {
let subscriber: Subscriber<string>;
const ob = new Observable(o => subscriber = o);
this.router.events.pipe(filter(e => e instanceof NavigationEnd)).subscribe((e: RouterEvent) => {
// indexOf ==> -1/index
const indexOfParam = e.url.indexOf('?');
const path = e.url.substr(0, indexOfParam === -1 ? e.url.length : indexOfParam);
// lastIndexOf ==> 0/index
const indexOf = path.lastIndexOf('/');
const prefix = path.substr(0, indexOf === 0 ? path.length : indexOf);
this.dealWithPathChange(prefix)
this.currentPath = prefix;
subscriber.next(prefix)
});
return ob;
}
private dealWithPathChange(path) {
// tslint:disable-next-line:forin
for (const visibleKey in this.visible) {
this.visible[visibleKey] = true
}
switch (path) {
case '/admin':
this.visible.header = false
this.visible.footer = false
this.visible.globalBackToTop = false
break
case '/user':
case '/write':
this.visible.footer = false
this.visible.globalBackToTop = false
break;
default:
}
}
}