Forked from KostyaEsmukov/_ express-redirect-platform-location.md
Created
March 1, 2017 14:39
-
-
Save PatrickJS/91ad71d4fa28f0e1ad697eba3b4d8da8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Injectable, Optional, Inject } from '@angular/core'; | |
import { APP_BASE_HREF } from '@angular/common'; | |
import { NodePlatformLocation, REQUEST_URL, ORIGIN_URL } from 'angular2-platform-node'; | |
import { Response, Request } from 'express'; | |
/** | |
* Issue HTTP 302 redirects on internal redirects | |
*/ | |
@Injectable() | |
export class ExpressRedirectPlatformLocation extends NodePlatformLocation { | |
// fix AOT by explicitly defining the constructor | |
// error TS2346: Supplied parameters do not match any signature of call target. | |
constructor(@Optional() @Inject(ORIGIN_URL) originUrl: string, | |
@Optional() @Inject(REQUEST_URL) requestUrl: string, | |
@Optional() @Inject(APP_BASE_HREF) baseUrl?: string) { | |
super(originUrl, requestUrl, baseUrl); | |
} | |
pushState(state: any, title: string, url: string): void { | |
let req: Request = Zone.current.get('req'); | |
let res: Response = Zone.current.get('res'); | |
if (url !== req.url) { // ?? Zone.current.get('requestUrl') | |
if (res.finished) { | |
console.warn('Attempted to redirect on a finished response. From', req.url, 'to', url); | |
} else { | |
console.log('Redirecting from', req.url, 'to', url); | |
res.redirect(url); | |
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. | |
} | |
} | |
return super.pushState(state, title, url); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { PlatformLocation } from '@angular/common'; | |
... | |
@NgModule({ | |
bootstrap: [ AppComponent ], | |
imports: [ | |
... | |
], | |
providers: [ | |
{ provide: PlatformLocation, useClass: ExpressRedirectPlatformLocation }, | |
... | |
], | |
}) | |
export class MainModule { | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment