Код универсального приложения Angular 6 не отображается в исходном представлении - PullRequest
0 голосов
/ 03 декабря 2018

Итак, у меня есть приложение, и оно состоит из двух страниц, и теперь, когда я просматриваю исходный код домашней страницы, я вижу код заголовка, код нижнего колонтитула, но не код тела ... теперь код тела хранится в <router-outlet></router-outlet>но когда я просматриваю вторую страницу terms-and-conditions, я вижу правильный код, отображаемый в исходном представлении.Я не уверен, почему он не работает на моей домашней странице ??

мой контейнер приложения структурирован так, что

<div class="loading"></div>
<app-header></app-header>
<router-outlet></router-outlet>
<app-footer></app-footer>

мои маршруты настроены так ...

import { NgModule } from '@angular/core';
import { RouterModule, Routes, Router } from '@angular/router';

// Components
import { HomeComponent } from './home/home.component';
import { TcComponent } from './tc/tc.component';

const routes: Routes = [
    {
        path: '',
        component: HomeComponent,
        pathMatch: 'full'
    },
    {
        path: 'terms-and-conditions',
        component: TcComponent
    }
];

@NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [ RouterModule ]
})
export class AppRoutingModule { }

мой server.ts

import 'zone.js/dist/zone-node';
import 'reflect-metadata';

import { enableProdMode } from '@angular/core';
import * as express from 'express';
import { join } from 'path';
const path = require('path');

// Faster server renders w/ Prod mode (dev mode never needed)
enableProdMode();

// SSL Redirect
const sslRedirect = require('heroku-ssl-redirect');
// Compression
const compression = require('compression');
// Express server
const app = express();

const PORT = process.env.PORT || 8080;
const DIST_FOLDER = join(process.cwd(), 'dist');
const APP_NAME = 'browser';

// * NOTE :: leave this as require() since this file is built Dynamically from webpack
const { AppServerModuleNgFactory, LAZY_MODULE_MAP } = 
require('./dist/server/main');

// Express Engine
import { ngExpressEngine } from '@nguniversal/express-engine';
// Import module map for lazy loading
import { provideModuleMap } from '@nguniversal/module-map-ngfactory-loader';

app.engine('html', ngExpressEngine({
  bootstrap: AppServerModuleNgFactory,
  providers: [
    provideModuleMap(LAZY_MODULE_MAP)
  ]
}));

app.use(sslRedirect());
app.use(compression());

app.set('view engine', 'html');
app.set('views', join(DIST_FOLDER, APP_NAME));

// TODO: implement data requests securely
app.get('/api/*', (req, res) => {
  res.status(404).send('data requests are not supported');
});

// Server static files from /browser
app.get('*.*', express.static(join(DIST_FOLDER, APP_NAME), {
  maxAge: '1y'
}));

// All regular routes use the Universal engine
app.get('*', (req, res) => {
  res.render('index', { req });
});

app.route('/sitemap.xml')
  .get((req, res) => {
    res.sendFile(path.resolve(path.join(__dirname, '/sitemap.xml')));
  });

// Start up the Node server
app.listen(PORT, () => {
  console.log(`Node server listening on http://localhost:${PORT}`);
});

Я не уверен, что может быть причиной этой проблемы, поэтому, пожалуйста, дайте мне знать, если вам нужна дополнительная информация

РЕДАКТИРОВАТЬ

Я пытался изменить конфигурацию маршрута, чтобы она выглядела следующим образом

{
   path: '',
   redirectTo: '/home',
   pathMatch: 'full'
},
{
   path: 'home',
   component: HomeComponent
}
...

, но это ничего не изменило

РЕДАКТИРОВАТЬ

home.component.ts

import { WINDOW } from '@ng-toolkit/universal';
import { Component, OnInit , Inject} from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {


constructor(
  @Inject(WINDOW) private window: Window,
) { }


ngOnInit() {
  this.startCarousel();
}

startCarousel() {
  this.sectionTwoInterval = setInterval(() => {
    this.next(1);
  }, 5000);
  this.sectionFourInterval = setInterval(() => {
    this.next(2);
  }, 5000);
}

goToSlide(carousel: number, slide: number) {
  switch (carousel) {
    case 1:
      clearInterval(this.sectionTwoInterval);
      this.sectionTwoActive = slide;
      break;
    case 2:
      clearInterval(this.sectionFourInterval);
      this.sectionFourActive = slide;
      break;
  }
}

next(carousel: number, stop?: boolean) {
  if (stop === true) { this.stopInterval(carousel); }
  switch (carousel) {
    case 1:
      if (this.sectionTwoActive !== this.sectionTwoImages.length - 1) {
        this.sectionTwoActive++;
      } else {
        this.sectionTwoActive = 0;
      }
      break;
    case 2:
      if (this.sectionFourActive !== this.sectionFourImages.length - 1) {
        this.sectionFourActive++;
      } else {
        this.sectionFourActive = 0;
      }
      break;
  }
}

back(carousel: number, stop?: boolean) {
  if (stop === true) { this.stopInterval(carousel); }
  switch (carousel) {
    case 1:
      if (this.sectionTwoActive !== 0) {
        this.sectionTwoActive--;
      } else {
        this.sectionTwoActive = this.sectionTwoImages.length - 1;
      }
      break;
    case 2:
      if (this.sectionFourActive !== 0) {
        this.sectionFourActive--;
      } else {
        this.sectionFourActive = this.sectionFourImages.length - 1;
      }
      break;
  }
}

stopInterval(carousel: number) {
  switch (carousel) {
    case 1:
      clearInterval(this.sectionTwoInterval);
      break;
    case 2:
      clearInterval(this.sectionFourInterval);
      break;
  }
}

}

Спасибо!

1 Ответ

0 голосов
/ 03 декабря 2018

Попробуйте эту конфигурацию:

 {
    path: 'home',
    component: HomeComponent
  },
  { path: '', //empty route
    redirectTo: '/home',
    pathMatch: 'full'
  },
...