Angular universal rendering for some routes only

2020-06-04 01:57发布

问题:

I was playing with angular universal a bit but cant find option to use server side rendering only for some pages like home page and render all other routes in standard angular way. I don't want to use server side rendering for private pages where SEO is not needed. I can configure routes in express like this

// send all requests to Angular Universal
// if you want Express to handle certain routes (ex. for an API) make sure you adjust this
app.get('/', ngApp);
app.get('/home', ngApp);
app.get('/about', ngApp);

Ideally I don't want to know about NodeJs at all and configure it on angular routes config with property like serverSide: true

const appRoutes: Routes = [
  //public route, I want server rendering for SEO
  { path: 'home', component: HomeComponent, serverSide: true },
  //private user profile page, SEO is not needed
  { path: 'user/profile/:id', component: UserProfileComponent },
];

回答1:

In your server.ts for routes you don't want to render just do as below

app.get('/api/**', (req, res) => { });

app.get('/app/**', (req, res) => {
  console.log('not rendering  app pages');
});

app.get('/auth/**', (req, res) => {
  console.log('not rendering auth page');
});

// All regular routes use the Universal engine

app.get('*', (req, res) => {
  res.render('index', { req });
});

Hope this helps.