Angular 9 SSR 404 Not Found Page with Status code

Create Server Side Response Service

@Injectable({
  providedIn: 'root'
})
export class ServerSideResponseService {
  private response: Response

  constructor(@Optional() @Inject(RESPONSE) response: any) {
    this.response = response
  }

  setNotFound(message="not found"): this {
    if (this.response) {
      this.response.statusCode = 404
      this.response.statusMessage = message
    }
    return this
  }
}

and use it in Not Found Component

@Component({
  selector: 'app-not-found',
  templateUrl: './not-found.component.html',
  styleUrls: ['./not-found.component.css']
})
export class NotFoundComponent implements OnInit {

  constructor(private ssr: ServerResponseService) {
    this.ssr.setNotFound();
  }
}

Reference
https://github.com/DSpace/dspace-angular/commit/015b439a39208da4515eb4d18e4d21640fce1df0

Leave a Comment