Я столкнулся с проблемой angular 7 с универсальным в моем приложении, на этой странице (https://machinesrentals.com/category/working-at-heights) он не откроется напрямую, если вы go на домашнюю страницу (https://machinesrentals.com/) из верхнего меню go в категорию, работающую на высоте, он откроется нормально, но если вы обновите sh страницу, она сломается, на любой другой странице все в порядке server.ts
import 'reflect-metadata';
import 'zone.js/dist/zone-node';
import {enableProdMode} from '@angular/core';
import {ngExpressEngine} from '@nguniversal/express-engine';
import {provideModuleMap} from '@nguniversal/module-map-ngfactory-loader';
import * as express from 'express';
import {join} from 'path';
enableProdMode();
export const app = express();
const PORT = process.env.PORT || 4200;
const DIST_FOLDER = join(process.cwd(), 'dist/browser');
const domino = require('domino');
const fs = require('fs');
const template = fs.readFileSync(join(DIST_FOLDER , 'index.html')).toString();
const win = domino.createWindow(template);
global['window'] = win;
global['DOMTokenList'] = win.DOMTokenList;
global['Node'] = win.Node;
global['Text'] = win.Text;
global['HTMLElement'] = win.HTMLElement;
global['navigator'] = win.navigator;
global['Event'] = win.Event;
global['Event']['prototype'] = win.Event.prototype;
Object.defineProperty(win.document.body.style, 'transform', {
value: () => {
return {
enumerable: true,
configurable: true
};
},
});
global['document'] = win.document;
global['CSS'] = null;
const {AppServerModuleNgFactory, LAZY_MODULE_MAP} = require('./dist/server/main');
app.engine('html', ngExpressEngine({
bootstrap: AppServerModuleNgFactory,
providers: [
provideModuleMap(LAZY_MODULE_MAP)
]
}));
app.set('view engine', 'html');
app.set('views', DIST_FOLDER);
app.get('*.*', express.static(DIST_FOLDER, {
maxAge: '1y'
}));
app.get('*', (req, res) => {
res.render('index', { req });
});
app.server.module.ts
import { NgModule } from '@angular/core';
import { ServerModule, ServerTransferStateModule } from '@angular/platform-server';
import { AppModule } from './app.module';
import { AppComponent } from './app.component';
@NgModule({
imports: [
AppModule,
ServerModule,
ServerTransferStateModule
],
bootstrap: [AppComponent],
})
export class AppServerModule { }
Компонент поиска
export class SearchResultGroupComponent implements OnInit, AfterViewInit {
constructor(@Inject(WINDOW) public window: Window,
public formBuilder: FormBuilder,
public appSRV: AppService,
private router: Router,
private route: ActivatedRoute,
@Inject(APP_BASE_HREF) private baseHref: string,
@Inject(PLATFORM_ID) private platformId: Object,
private pagerSRV: PagerService,
private productSRV: ProductService,
private cartSRV: CartService,
private categorySRV: CategoryService,
public helperSRV: HelpersService,
private headerSRV: HeaderService,
public langSRV: LanguageService,
public titleSRV: Title,
public translate: TranslateService,
private toastr: NotificationService,
public dialog: MatDialog,
private _renderer2: Renderer2,
@Inject(DOCUMENT) private _document
) {
if (navigator.userAgent.indexOf('MSIE') !== -1 || navigator.appVersion.indexOf('Trident/') > -1) {
this.isIELimitApplied = true;
this.generateRND = 12234354354;
} else {
this.generateRND = Math.floor(Math.random() * 90000) + 10000;
}
// console.log(this.currentLang)
this.currentLangWithSlash = this.helperSRV.checkDefaultLang(this.currentLang);
// console.log(this.currentLangWithSlash)
this.setAndGetIsLoggedIn();
this.currentUrl = this.router.url;
this.helperSRV.setLocalStorage('srh_search_url', this.router.url);
this.baseUrl = baseHref + 'assets/';
//if (window.innerWidth > this.maxResolution) this.isSideBar = false;
translate.get('searchResult.pageTitle').subscribe((res: string) => {
titleSRV.setTitle('Rentaga - ' + res);
});
}
setAndGetIsLoggedIn() {
this.headerSRV.setIsLoggedIn(this.appSRV.loggedIn('search'));
this.headerSRV.isLoggedIn.subscribe(updatedName => {
this._isLoggedIn = updatedName || false;
});
}
ngAfterViewInit() {
this.catNameURI = this.route.snapshot.paramMap.get('catname') || '0';
this.subCatNameURI = this.route.snapshot.paramMap.get('subcatname') || '0';
let apislug = this.subCatNameURI;
if (this.subCatNameURI === '0') {
apislug = this.catNameURI;
}
console.log("ngAfterViewInit", this.catNameURI, this.subCatNameURI, apislug);
this.helperSRV.getMetaData(apislug, this.currentLang).subscribe(rs => {
const seoData = rs.data || null;
this.catDesc = seoData.catDescription;
this.catImg = seoData.ogImage;
this.helperSRV.settingSEoData(seoData, this.currentLang);
}, err => {
});
}
ngOnDestroy() {
this.helperSRV.setLocalStorage('currentPage', '');
}
ngOnInit() {
this.helperSRV.setLocalStorage('currentPage', '');
//$(document).foundation();
this.dropdownSettings = {
singleSelection: false,
idField: 'id',
textField: 'name',
selectAllText: 'Select All',
unSelectAllText: 'UnSelect All',
//itemsShowLimit: 3,
allowSearchFilter: true
};
this.onResize();
this.createForm();
this.resetingSubCat();
this.onChangesInForm();
const latlong = this.helperSRV.getLocalStorage('srh_latLong').toString() || '0';
if (latlong !== '0') {
const splitedLatLong = latlong.toString().split(',');
this.selectedLat = splitedLatLong[0];
this.selectedLong = splitedLatLong[1];
}
this.catNameURI = this.route.snapshot.paramMap.get('catname') || '0';
this.subCatNameURI = this.route.snapshot.paramMap.get('subcatname') || '0';
if (this.catNameURI !== undefined) {
// console.log(this.route.snapshot.data.seo.data);
// this.helperSRV.settingSEoData(this.route.snapshot.data.seo.data, this.currentLang)
this.IsCategorySearch = true;
this.getCategories();
} else {
this.IsCategorySearch = false;
this.gettingParams();
}
this.setRefineSearchErro();
}
getSearchResult(criteria, params) {
this.load = false;
this.response = this.productSRV.searchProductGroup(criteria).pipe(
// side effect
tap(success => {
if (success.error.length !== 0) {
this.toastr.showToaster(success.error[0], 'Error!', true);
//alert('d');
} else {
this.searchResults = [];
this.searchResults = success.data;
let productsJson = [];
success.data.forEach((row, ind) => {
const catSlug = this.helperSRV.getLangConversionByIndex(row.productSearchResults[0].category, 'category_slug');
const subcatSlug = this.helperSRV.getLangConversionByIndex(row.productSearchResults[0].category, 'parent_category_slug');
const orgSlug = this.helperSRV.makeSlug(row.productSearchResults[0].organization_name);
const productSlug = row.productSearchResults[0].slug;
productsJson.push({
'@type': 'ListItem',
'position': ind + 1,
'url': `https://rentaga.com/product/${catSlug}/${subcatSlug}/${orgSlug}/${productSlug}`
})
})
this.productsJsonLD = {
'@context': 'http://schema.org',
'@type': 'ItemList',
'itemListElement': productsJson
};
this.setJsonLd(this.productsJsonLD);
//console.log(this.productsJsonLD)
//this.window.scroll(0, 0)
//rs.resultsCount = 200;
this.totalItems = success.resultsCount;
this.totalPages = Math.ceil(this.totalItems / this.pageSize);
//this.pages = this.setPages(this.totalPages, this.currentPage);
this.pages = this.pagination(this.currentPage, this.totalPages);
//console.log(this.pagination(this.currentPage, this.totalPages));
//if (!this.IsCategorySearch) {
//this.createForm();
//console.log(rs);
this.filterCategories = [];
this.langfilterCategories = [];
if (success.filteredCategories.length > 0) {
const newFilteredCat = this.helperSRV.getLangConversionByIndex2(success.filteredCategories, 'values');
const newFilteredCatEN = this.helperSRV.getLangConversionByIndex2ReturnEn(success.filteredCategories, 'values');
if (newFilteredCat.length > 0) {
this.filterCategories = newFilteredCatEN;
this.langfilterCategories = newFilteredCat;
this.updateFilter();
}
let manufacturers__ = '';
let keywords__ = '';
this.filterCategories.forEach(element => {
// console.log(element)
if (element.name === 'Manufacturer') {
manufacturers__ = element.selected_value.join(',');
}
keywords__ += element.name + ',';
});
// console.log(manufacturers__, keywords__)
}
// console.log(this.langfilterCategories);
this.isFacetsAvailable = true;
this.langfilterCategories.filter(lfc => {
if (!lfc.minMaxEqual) {
this.isFacetsAvailable = false;
}
})
this.setFormValues(params);
if (this.window.innerWidth <= this.maxResolution) {
if (!this.isSideBar) this.toggleSideBar();
}
//}
this.setClasses(); // setting bydefault list
this.setPage(this.currentPage);
this.load = true;
this.isClicked = false;
// console.log(this.form.value)
}
}),
// mapping result to the array we need
tap(console.log),
map(success => success.data),
// catching error
catchError(error => {
this.setFormValues(params);
// if (error.error.error.length > 0)
// this.toastr.showToaster(error.error.error[0], 'Error!', true);
// else
// this.toastr.showToaster(error.error.message, 'Error!', true);
this.load = true;
console.log('ERROR!', error);
// console.log('Error!', error);
throw error;
}),
);
}
async getCategories() {
await this.categorySRV.gets().subscribe(rs => {
if (rs.error.length !== 0) {
//console.log(rs.error);
} else {
this.categories = [];
this.categories = rs.data;
this.getCatIdByCatSlug(this.catNameURI, this.subCatNameURI);
this.gettingParams();
}
});
}
}
Компонент поиска html
<ng-container *ngIf="response | async as searchResults;">
<ng-container *ngIf="load && searchResults?.length > 0">
<div class="column" *ngFor="let search of searchResults; let h = index">
</div>
</ng-container>
</ng-container>
Также не получает источник страницы, который мне нужен дождаться api
const latlong = this.helperSRV.getLocalStorage('srh_latLong').toString() || '0';
некоторое время работает нормально, когда я удалил .toString()
, а также получил переменную перевода в Pagesource, заранее спасибо, если вы мне помогли