我有一个让我感到沮丧的问题。
我似乎无法以角度5提供404状态。
已采取的步骤:
在server.ts中,我导入了
const { AppServerModuleNgFactory, LAZY_MODULE_MAP } = require(`./dist-server/main.${hash}.bundle`);
import { ngExpressEngine } from '@nguniversal/express-engine';
import { REQUEST, RESPONSE } from '@nguniversal/express-engine/tokens';
并添加
app.engine('html', (_, options, callback) =>
ngExpressEngine({
bootstrap: AppServerModuleNgFactory,
providers: [
provideModuleMap(LAZY_MODULE_MAP),
{
provide: REQUEST,
useValue: options.req,
},
{
provide: RESPONSE,
useValue: options.req.res,
},
]
})(_, options, callback)
);
在我实际未找到的组件中,
import { Component, Inject, Injector, OnInit, PLATFORM_ID } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';
import { RESPONSE } from '@nguniversal/express-engine/tokens';
import { Response } from 'express';
@Component({
selector: 'not-found',
templateUrl: './not-found.component.html',
styleUrls: ['./not-found.component.scss']
})
export class NotFoundComponent implements OnInit {
constructor(
@Inject(PLATFORM_ID) private platformId: Object,
@Inject(Injector) private injector: Injector
) {}
ngOnInit() {
const response = this.injector.get(RESPONSE) as Response;
response.status(404);
}
}
}
我正在localhost上运行它,并且正在执行以下实现: https://blog.thecodecampus.de/angular-universal-handle-404-set-status-codes/
在评论部分,我们被告知将@Optional()@Inject(RESPONSE)私有响应:Response)替换为@Inject(Injector)私有注入器:Injector。
答案 0 :(得分:0)
仅当在预渲染期间在服务器端执行代码时提供Express
Response
对象,而一旦客户端执行接管了则不提供。因此,您在bwoser(客户端)中遇到的错误
如果您将响应指定为Optional
import {Optional} from '@angular/core';
constructor(@Inject(PLATFORM_ID) private platformId: Object,
@Inject(RESPONSE) private response: Response)
{
//Here response will be null on client side, and contain Express Response instance on server side
}
或者,如果您想直接使用Injector
实例(不知道为什么要这样做,除非遇到循环依赖问题),您只需要在客户端使用它< / p>
import {isPlatformServer} from '@angular/common';
ngOnInit()
{
if(isPlatformServer(this.platformId))//Only executes server side
{
const response = this.injector.get(RESPONSE) as Response;
response.status(404);
}
}
答案 1 :(得分:-1)
我的路由文件夹中没有设置我的页面,因此看起来像这样
{ Path: '**', component: PageNotFoundComponent }
这意味着,如果您点击了mysite.com/askgdcaksgdf
,则将获得404页面的服务。