I need to generate an id in order to save on DB the last filter aplied by my filter component. the problem is that the filter component have instances in several parts of my app and I need a way to generate a persitant id for each of the instances in order to save to the DB.
I tried with the nghost attribuete but this one is the same in each instance.
private getId(): any {
const id = this.constructor['ɵcmp'].id;
return id;
}
I can not depend on random generation because the id generated may change if the user change the host or the browser. Is there a way to acomplish this?
this is my current sampler
In my last attempt I add a static number var in order to get a counter for the components then add this conter to the host id
export class ChildComponent {
static index = 0;
unique = this.constructor['ɵcmp'].id + ChildComponent.index;
constructor() {
ChildComponent.index ++;
}
}
This solution do not offer all I need because the generate ID can variyin depending of the order of execution of the different filters, this may caus that two filters in two diferent routes of the app get the same id.
To prevent this I add the Router service in order to get the current url:
constructor(private router: Router) {
ChildComponent.index ++;
this.unique = btoa(this.constructor['ɵcmp'].id + ChildComponent.index + this.router.url);
}
Now I realize that if we navigate directly by url or if we navigate from the home page we get a different id for the same component instance.
If you want to create one Identifier for each instance of the component you can create your own GUID and give it to your variable unique. A working example:
export class ChildComponent implements OnInit{
unique = '';
ngOnInit() {
this.unique = this.uuidv4()
}
uuidv4() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With