redoc/lib/services/hash.service.ts

53 lines
1.2 KiB
TypeScript
Raw Normal View History

2016-05-07 10:54:44 +03:00
'use strict';
2016-10-23 20:18:42 +03:00
import { Injectable } from '@angular/core';
import { PlatformLocation } from '@angular/common';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
2016-05-07 10:54:44 +03:00
2017-05-12 11:21:47 +03:00
import { debounce } from '../utils/';
2016-05-07 10:54:44 +03:00
@Injectable()
export class Hash {
2016-11-23 02:23:32 +03:00
public value = new BehaviorSubject<string | null>(null);
private noEmit:boolean = false;
2017-05-12 11:21:47 +03:00
private debouncedUpdate: (hash:string, rewrite: boolean) => void;
2016-11-24 16:29:29 +03:00
constructor(private location: PlatformLocation) {
2016-05-07 10:54:44 +03:00
this.bind();
2017-05-12 11:21:47 +03:00
this.debouncedUpdate = debounce(this._update.bind(this), 100);
2016-11-24 16:29:29 +03:00
}
2016-05-07 10:54:44 +03:00
2016-11-24 16:29:29 +03:00
start() {
this.value.next(this.hash);
2016-05-07 10:54:44 +03:00
}
get hash() {
2016-10-23 20:18:42 +03:00
return this.location.hash;
2016-05-07 10:54:44 +03:00
}
bind() {
2016-10-23 20:18:42 +03:00
this.location.onHashChange(() => {
if (this.noEmit) return;
2016-10-23 20:18:42 +03:00
this.value.next(this.hash);
2016-05-07 10:54:44 +03:00
});
}
update(hash: string|null, rewriteHistory:boolean = false) {
2017-05-12 11:21:47 +03:00
this.debouncedUpdate(hash, rewriteHistory);
}
private _update(hash: string|null, rewriteHistory:boolean = false) {
if (hash == undefined) return;
if (rewriteHistory) {
2017-04-23 18:00:36 +03:00
window.history.replaceState(null, '', window.location.href.split('#')[0] + '#' + hash);
return;
}
this.noEmit = true;
window.location.hash = hash;
setTimeout(() => {
this.noEmit = false;
});
}
2017-05-12 11:21:47 +03:00
2016-05-07 10:54:44 +03:00
}