Angular, Web Development

Angular 6.x – 404 page with correct header using Angular Universal

Based on my previous post about adding a 404 page in Angular 4.x, I have added a tweak to return the correct 404 status code header. This process, however, requires the Angular Universal integration. This post assumes that you already know how to setup your Angular application with Angular Universal.

The original 404 component

Based on my previous post, here is what the 404 page component looks like:

import { Component } from '@angular/core';
 
@Component({
  selector: 'app-notfound',
  templateUrl: './notfound.component.html'
})
 
export class NotfoundComponent { }

Adding the 404 status code

I have already upgraded to Angular 6.x since the Angular Universal integration. I have ditched my old ExpressJS server and replaced it with Angular Universal, which is still ExpressJS by the way. To be able to support both the client-side and server side (Universal), we need to know which environment we are running. Below is the full component code after my Angular Universal migration.

import { Component, OnInit, Optional } from '@angular/core';
import { PLATFORM_ID, APP_ID, Inject } from '@angular/core';
import { Title } from "@angular/platform-browser";
import { isPlatformBrowser } from '@angular/common';
import { RESPONSE } from "@nguniversal/express-engine/tokens";
import { Response } from 'express';

@Component({
  selector: 'app-notfound',
  templateUrl: './notfound.component.html'
})

export class NotfoundComponent implements OnInit {

  constructor(
    @Inject(PLATFORM_ID) private platformId: Object,
    @Inject(APP_ID) private appId: string,
    @Optional() @Inject(RESPONSE) private response: Response,
    private titleService: Title
  ) {
    this.titleService.setTitle('Lysender - Page Not Found');
  }

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

We only show the status code when we are not running in the browser platform, ie: running on the server.

That’s it!

5 thoughts on “Angular 6.x – 404 page with correct header using Angular Universal”

  1. @lysender thanks for reply . But in my case it only set header . Template doesn’t run when i give dependency Injection of Platform Id ,and Response in constructor . Please help..!!

  2. I am using Angular 6 and using lazy loading . When 404 component load it set headers and template doesn’t reflect . Please help stuck in this.

Leave a reply

Your email address will not be published. Required fields are marked *