redoc/lib/services/hash.service.ts

43 lines
955 B
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';
2016-05-07 10:54:44 +03:00
2016-10-23 20:18:42 +03:00
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
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;
2016-11-24 16:29:29 +03:00
constructor(private location: PlatformLocation) {
2016-05-07 10:54:44 +03:00
this.bind();
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) {
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;
});
}
2016-05-07 10:54:44 +03:00
}