简体   繁体   中英

Prevent reloading of angular component while refreshing page

I have Single Page Application website, written in angular 4+. I have so many components likes as FilterComponent, SideBarMenuComponent, HeaderComponent, FooterComponent, etc.

I want to prevent reloading of SideBarComponent to be initiated of ngOnInit when user refresh whole page. How can I do prevent ngOnInit method not to run for only SideBarMenuComponent so that whatever is user selected in side bar menu, it wont get removed.

Please let me know if you did not get understand in comment section.

When user reload your SPA application then your every component must reload .

You can store user's selected menu in local storage. So when user reload your app you can check previous selected menu

I think you can achieve this using Angular pushState :

https://angular.io/guide/router

As a matter of fact, as a coincidence, the link from the Angular documentation I included does exactly this too. If you go to the link above and refresh the page, the navigation on the left of the page stays the same, even if the page reloads.

Note that pushState requires server side support, meaning that the server needs to return the Angular app index.html instead of a 404. This is slightly more complex issue, but if, like me, you serve your Angular app from a Node.js backend (which is not an amazing idea), you can use this script:

const express = require('express');
const serveStatic = require('serve-static');
const compression = require('compression');
const port = process.env.PORT || 3000;
const domain =  process.env.DOMAIN;

function ensureDomain(req, res, next) {
  if (!domain || req.hostname === domain) {
    // OK, continue
    return next();
  }

  // handle port numbers if you need non defaults
  res.redirect(`http://${domain}${req.url}`);
}

const app = express();

// at top of routing calls
app.all('*', ensureDomain);

app.use(compression());

// default to .html (you can omit the extension in the URL)
app.use(serveStatic(`${__dirname}/dist`, {
  'extensions': ['html'],
  etag: true
}));

app.get('*', function(req, res){
  res.sendFile(`${__dirname}/dist/index.html`);
});

app.listen(port, () => {
  console.log('Server running...');
});

Note the lines:

app.get('*', function(req, res){
  res.sendFile(`${__dirname}/dist/index.html`);
});

which serve any request that hasn't been handled, with index.html (effectively instead of a 404).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM