Reputation: 632
I am working on an angular web application where I want to show the user messages about different actions (like success, failure, etc.). These messages are set to clear automatically after 10 seconds, or when the user clicks the x
button beside every alert. This is the easy part.
The difficult part is - I want to maintain these messages when the user navigates to different parts of the application. Something like facebook/google chat boxes.
I initially went through some ideas and decided on a solution where I stored the messages in an array in the local storage and every web page had code to look for these messages and display them if found.
But, I faced issues with the timing of the messages disappearing automatically (the timer reset to 10 seconds for all messages on page load). And also whenever the URL changed, the messages would go away and would load as new alerts after the new web page finished loading.
What is the correct way of doing this?
Upvotes: 0
Views: 108
Reputation: 3556
I would consider treating your Message
component as a singleton, i.e. it only ever has one instance. If the Message
component is a child to other components, then it will be removed when it's parent component is removed from the DOM.
Consider moving your messages component to the root/app level (i.e. inside your AppComponent
). This way as the user navigates around your app, the Messages
component will always be visible. Further, the state of the notifications can be stored within this Messages
component, so it's own timer wouldn't be affected by the rendering/removal of other components.
This all assumes you aren't using some sort of global store for your app state. If you are, consider Hyun Woo Krassilchikoff's answer which details implementing a global NGRX store.
Upvotes: 1
Reputation: 9
The most efficient way is actually to use an NGRX store for your error message and a unique component in the main layout of your application rendering any message streamed from the store.
You'd need:
Upvotes: 0
Reputation: 3230
Using your implementation, the timeout issue is easy to fix: when you store the alert, include an epiresAfter
property as well. This property would be a timestamp af when you expect the the alert to no longer display.
Then you set up a timeout that either:
Upvotes: 1
Reputation: 1221
Whenever an alert appears in your application, you can store its timestamp together with the message. And on the page load call setTimeout
for each alert with a callback of removing this message and the time difference between now and the timestamp+10sec.
Upvotes: 1