将组件的状态交给服务来控制
This commit is contained in:
16
index/src/app/services/component-state.service.spec.ts
Normal file
16
index/src/app/services/component-state.service.spec.ts
Normal 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();
|
||||
});
|
||||
});
|
||||
61
index/src/app/services/component-state.service.ts
Normal file
61
index/src/app/services/component-state.service.ts
Normal 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:
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user