Skip to content

fix: Catch router errors #21

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 21 commits into from
Aug 5, 2021
Merged
Show file tree
Hide file tree
Changes from 16 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 1 addition & 3 deletions demo/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,8 @@
"@angular/platform-server": "~12.0.4",
"@angular/router": "~12.0.4",
"@netlify/functions": "^0.7.2",
"@nguniversal/express-engine": "^12.0.1",
"@nguniversal/express-engine": "~12.0.1",
"adm-zip": "^0.5.5",
"aws-serverless-express": "^3.4.0",
"express": "^4.17.1",
"rxjs": "~7.1.0",
"tslib": "^2.2.0",
"zone.js": "~0.11.4"
Expand Down
25 changes: 16 additions & 9 deletions demo/src/app/app-routing.module.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,27 @@
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HeroesComponent } from './heroes/heroes.component';
import { DashboardComponent } from './dashboard/dashboard.component';
import { HeroDetailComponent } from './hero-detail/hero-detail.component';
import { CommonModule } from '@angular/common'
import { NgModule } from '@angular/core'
import { RouterModule, Routes } from '@angular/router'
import { HeroesComponent } from './heroes/heroes.component'
import { DashboardComponent } from './dashboard/dashboard.component'
import { HeroDetailComponent } from './hero-detail/hero-detail.component'
import { NotFoundComponent } from './not-found/not-found.component'

const routes: Routes = [
{ path: '', redirectTo: '/dashboard', pathMatch: 'full' },
{ path: 'dashboard', component: DashboardComponent },
{ path: 'detail/:id', component: HeroDetailComponent },
{ path: 'heroes', component: HeroesComponent },
];
{ path: '**', component: NotFoundComponent },
]

@NgModule({
imports: [RouterModule.forRoot(routes, {
initialNavigation: 'enabled'
})],
imports: [
CommonModule,
RouterModule.forRoot(routes, {
initialNavigation: 'enabled',
}),
],
exports: [RouterModule],
declarations: [DashboardComponent, HeroDetailComponent, HeroesComponent, NotFoundComponent],
})
export class AppRoutingModule {}
17 changes: 7 additions & 10 deletions demo/src/app/app.module.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,13 @@
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { NgModule } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { FormsModule } from '@angular/forms'

import { AppComponent } from './app.component';
import { HeroesComponent } from './heroes/heroes.component';
import { HeroDetailComponent } from './hero-detail/hero-detail.component';
import { MessagesComponent } from './messages/messages.component';
import { AppRoutingModule } from './app-routing.module';
import { DashboardComponent } from './dashboard/dashboard.component';
import { AppComponent } from './app.component'
import { AppRoutingModule } from './app-routing.module'
import { MessagesComponent } from './messages/messages.component'

@NgModule({
declarations: [AppComponent, HeroesComponent, HeroDetailComponent, MessagesComponent, DashboardComponent],
declarations: [AppComponent, MessagesComponent],
imports: [BrowserModule.withServerTransition({ appId: 'serverApp' }), FormsModule, AppRoutingModule],
providers: [],
bootstrap: [AppComponent],
Expand Down
16 changes: 8 additions & 8 deletions demo/src/app/app.server.module.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import { NgModule } from '@angular/core';
import { ServerModule } from '@angular/platform-server';
import { PlatformLocation } from '@angular/common'
import { NgModule } from '@angular/core'
import { ServerModule } from '@angular/platform-server'

import { AppModule } from './app.module';
import { AppComponent } from './app.component';
import { AppModule } from './app.module'
import { AppComponent } from './app.component'
import { ExpressRedirectPlatformLocation } from './express-redirect-platform-location.service'

@NgModule({
imports: [
AppModule,
ServerModule,
],
imports: [AppModule, ServerModule],
bootstrap: [AppComponent],
providers: [{ provide: PlatformLocation, useClass: ExpressRedirectPlatformLocation }],
})
export class AppServerModule {}
81 changes: 81 additions & 0 deletions demo/src/app/express-redirect-platform-location.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import { Injectable, Inject, Optional } from '@angular/core';
import { Response, Request } from 'express';
import { DOCUMENT } from '@angular/common';
import { INITIAL_CONFIG, ɵINTERNAL_SERVER_PLATFORM_PROVIDERS } from '@angular/platform-server';
import { PlatformLocation } from '@angular/common';
import { REQUEST, RESPONSE } from '@nguniversal/express-engine/tokens';

/**
* This service can't be tested with karma, because tests are run in a browser,
* but `express` is imported here, which requires `http` module of NodeJS.
*/

// https://github.com/angular/angular/issues/13822#issuecomment-283309920

interface IPlatformLocation {
pushState(state: any, title: string, url: string): any;
replaceState(state: any, title: string, url: string): any;
}

// This class is not exported
const ServerPlatformLocation: new(_doc: any, _config: any) => IPlatformLocation =
(ɵINTERNAL_SERVER_PLATFORM_PROVIDERS as any)
.find(provider => provider.provide === PlatformLocation)
.useClass;


/**
* Issue HTTP 302 redirects on internal redirects
*/
@Injectable()
export class ExpressRedirectPlatformLocation extends ServerPlatformLocation {

constructor(
@Inject(DOCUMENT) _doc: any,
@Optional() @Inject(INITIAL_CONFIG) _config: any,
@Inject(REQUEST) private req: Request,
@Inject(RESPONSE) private res: Response,
) {
super(_doc, _config);
}

private redirectExpress(state: any, title: string, url: string) {
if (url === this.req.url) return;

if (this.res.finished) {
const req: any = this.req;
req._r_count = (req._r_count || 0) + 1;

console.warn('Attempted to redirect on a finished response. From',
this.req.url, 'to', url);

if (req._r_count > 10) {
console.error('Detected a redirection loop. killing the nodejs process');
// tslint:disable-next-line
console.trace();
console.log(state, title, url);
process.exit(1);
}
} else {
let status = this.res.statusCode || 0; // attempt to use the already set status
if (status < 300 || status >= 400) status = 302; // temporary redirect
console.log(`Redirecting from ${this.req.url} to ${url} with ${status}`);
this.res.redirect(status, url);
this.res.end();
// I haven't found a way to correctly stop Angular rendering.
// So we just let it end its work, though we have already closed
// the response.
}
}

pushState(state: any, title: string, url: string): any {
this.redirectExpress(state, title, url);
return super.pushState(state, title, url);
}

replaceState(state: any, title: string, url: string): any {
this.redirectExpress(state, title, url);
return super.replaceState(state, title, url);
}

}
Empty file.
1 change: 1 addition & 0 deletions demo/src/app/not-found/not-found.component.html
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<p>Page not found: {{ path | async }}</p>
25 changes: 25 additions & 0 deletions demo/src/app/not-found/not-found.component.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';

import { NotFoundComponent } from './not-found.component';

describe('NotFoundComponent', () => {
let component: NotFoundComponent;
let fixture: ComponentFixture<NotFoundComponent>;

beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ NotFoundComponent ]
})
.compileComponents();
});

beforeEach(() => {
fixture = TestBed.createComponent(NotFoundComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});

it('should create', () => {
expect(component).toBeTruthy();
});
});
27 changes: 27 additions & 0 deletions demo/src/app/not-found/not-found.component.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { Component, Inject, OnInit, Optional } from '@angular/core'
import { RESPONSE } from '@nguniversal/express-engine/tokens'
import { ActivatedRoute } from '@angular/router'
import { Observable } from 'rxjs'
import { map } from 'rxjs/operators'

@Component({
selector: 'app-not-found',
templateUrl: './not-found.component.html',
styleUrls: ['./not-found.component.css'],
})
export class NotFoundComponent implements OnInit {
private response: Response
path: Observable<string>

constructor(route: ActivatedRoute, @Optional() @Inject(RESPONSE) response: any) {
this.response = response
this.path = route.url.pipe(map((segments) => segments.join('/')))
}

ngOnInit(): void {
if (this.response) {
// @ts-ignore
this.response.status(404)
}
}
}
Loading