我认为您可以使用 Angular pushState 来实现这一点:
https://angular.io/guide/router
事实上,巧合的是,我包含的 Angular 文档中的链接也正是这样做的。如果您转到上面的链接并刷新页面,页面左侧的导航保持不变,即使页面重新加载。
请注意,pushState 需要服务器端支持,这意味着服务器需要返回 Angular 应用程序 index.html 而不是 404。这是一个稍微复杂的问题,但如果像我一样,您从节点提供 Angular 应用程序.js 后端(这不是一个了不起的想法),你可以使用这个脚本:
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...');
});
注意以下几行:
app.get('*', function(req, res){
res.sendFile(`${__dirname}/dist/index.html`);
});
使用index.html(有效地代替 404)处理任何尚未处理的请求。