找不到路线时检索404状态。 Angular 6+和Universal

问题描述 投票:4回答:1

我已经使用Universal发布了我的项目,并在.htaccess中指定所有请求都应该转到index.html(Angular应用程序的根页)

正如在这里被问到的那样:https://angular.io/guide/universal

它允许共享链接并打开URL中指定的组件

此外,如果打开了错误的路线,则创建一个组件:Handling 404 with Angular2

export const routes:RouterConfig = [
  ...Routes,
  // Show the 404 page for any routes that don't exist.
  { path: '**', component: Four04Component }
];

问题是搜索引擎将Four04Component视为具有200 OK状态而非错误页面的简单页面。你知道如何与Four04Component一起检索404错误吗?

angular search-engine angular-universal
1个回答
4
投票

您必须将响应注入角度应用程序,以实现首先更改server.ts中的这些行:

app.get('*', (req, res) => { //you can find these line easily
res.render('index', {
    req: req,
    res: res,
    providers: [
        {
            provide: REQUEST, useValue: (req)
        },
        {
            provide: RESPONSE, useValue: (res)
        }
    ]
    });
});

然后在你的Four04组件注入响应中,如下所示:

constructor(@Optional() @Inject(RESPONSE) private response: Response,
            @Inject(PLATFORM_ID) private platformId: Object) {}

之后,只需尝试使用Four04组件的ngoninit:

ngOnInit(){
    if(isPlatformServer(this.platformId)){
        this.response.status(404);
    }
}

希望这些能帮助别人。

© www.soinside.com 2019 - 2024. All rights reserved.