Skip to content

Instantly share code, notes, and snippets.

@psamsotha
Created July 8, 2016 04:28
Show Gist options
  • Save psamsotha/46bfff5361f622e3eba148d98941fa9d to your computer and use it in GitHub Desktop.
Save psamsotha/46bfff5361f622e3eba148d98941fa9d to your computer and use it in GitHub Desktop.
Get external configuration file before bootstrap in Angular 2. See also https://blog.sstorie.com/providing-external-data-when-bootstrapping-angular-2/
import { bootstrap } from '@angular/platform-browser-dynamic';
import { HTTP_PROVIDERS } from '@angular/http';
import { Http,
Request,
Response,
XSRFStrategy,
CookieXSRFStrategy } from '@angular/http';
import { Injector,
ReflectiveInjector } from '@angular/core';
import { Observable } from 'rxjs/Rx';
import { Configuration } from './config/configuration';
import { AppComponent } from './app.component';
export function configureAndRunApplication(configUrl: string) {
let http: Http = getHttp();
getConfig(http)
.then((json: string) => {
let configuration: Configuration = Configuration.fromJson(json);
bootstrap(AppComponent, [
HTTP_PROVIDERS,
{ provide: 'app.config', useValue: configuration }
]);
}, handleError);
function getConfig(http: Http): Promise<string> {
return http.get(configUrl)
.map((response: Response) => {
return response.text();
})
.catch(handleError)
.toPromise();
}
function getHttp(): Http {
let injector: Injector = ReflectiveInjector.resolveAndCreate([
...HTTP_PROVIDERS,
{ provide: XSRFStrategy, useValue: new NoCheckCookieXSRFStrategy() }
]);
return injector.get(Http);
}
function handleError(error: any) {
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg);
return Observable.throw(errMsg);
}
}
/**
* This is required as we are not using the platform brower. The original
* CookieXSRFStrategy would call the platform browser to get the cookies.
* We don't need it here, as we are just making a simple GET request
* to get the configuration file. The main application will not be using
* this or the custom made `Http` object.
*/
class NoCheckCookieXSRFStrategy extends CookieXSRFStrategy {
configureRequest(request: Request) {
// noop
}
}
@psamsotha
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment