Skip to content

Instantly share code, notes, and snippets.

@sdornan
Last active September 2, 2016 00:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sdornan/16af5105f09b69acce92402930c10757 to your computer and use it in GitHub Desktop.
Save sdornan/16af5105f09b69acce92402930c10757 to your computer and use it in GitHub Desktop.
angular2-rc5 Circular Dependency Code
import { Component, ViewEncapsulation, ViewContainerRef } from '@angular/core';
@Component({
selector: 'app',
template: require('./app.component.pug'),
styles: [require('./app.component.scss')],
encapsulation: ViewEncapsulation.None
})
export class AppComponent {
loaded: boolean = false;
constructor(private viewContainerRef: ViewContainerRef) {
this.viewContainerRef = viewContainerRef;
this.loaded = true;
}
}
import { NgModule, ApplicationRef } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpModule } from '@angular/http';
import { FormsModule } from '@angular/forms';
import { Ng2BootstrapModule } from 'ng2-bootstrap/ng2-bootstrap';
import { AuthHttp, provideAuth } from 'angular2-jwt';
import { RfpsModule } from './rfps';
import { AppComponent } from './app.component';
import { routing } from './app.routing';
import { HomeComponent } from './home';
import { Config, AuthGuard, AuthService, NavbarComponent, UserService } from './shared';
import { removeNgStyles, createNewHosts } from '@angularclass/hmr';
@NgModule({
imports: [
BrowserModule,
HttpModule,
FormsModule,
routing,
Ng2BootstrapModule,
// RfpsModule
],
declarations: [
AppComponent,
HomeComponent,
NavbarComponent
],
providers: [
AuthHttp,
provideAuth({
globalHeaders: [
{'Accept': 'application/vnd.groups360.com; version=1'},
{'Content-Type': 'application/json'}
]
}),
AuthGuard,
UserService
],
bootstrap: [AppComponent]
})
export class AppModule {
constructor(public appRef: ApplicationRef) {}
hmrOnInit(store) {
console.log('HMR store', store);
}
hmrOnDestroy(store) {
let cmpLocation = this.appRef.components.map(cmp => cmp.location.nativeElement);
// recreate elements
store.disposeOldHosts = createNewHosts(cmpLocation);
// remove styles
removeNgStyles();
}
hmrAfterDestroy(store) {
// display new elements
store.disposeOldHosts();
delete store.disposeOldHosts;
}
}
import { ModuleWithProviders } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home';
// import { rfpRouting } from './rfps';
// import { propertiesRoutes } from './properties';
import { AuthGuard } from './shared';
const appRoutes: Routes = [
// {
// path: '',
// redirectTo: '/rfps',
// pathMatch: 'full'
// },
// ...rfpRoutes,
// ...propertiesRoutes,
{ path: '**', component: HomeComponent, canActivate: [AuthGuard] }
];
export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);
import { Injectable } from '@angular/core';
import { Location } from '@angular/common';
import { Router, } from '@angular/router';
import { tokenNotExpired, JwtHelper } from 'angular2-jwt';
import { Config } from './config';
@Injectable()
export class AuthService {
public jwtHelper: JwtHelper;
constructor(private location: Location, private router: Router, private config: Config) {
this.jwtHelper = new JwtHelper();
}
login() {
const redirectUri = this.config.get('REDIRECT_URI');
const idServiceUri = this.config.get('ID_SERVICE_URL');
const clientId = this.config.get('CLIENT_ID');
const encodedRedirectUri = encodeURIComponent(redirectUri);
window.location.href = idServiceUri + '/oauth/authorize' +
`?client_id=${clientId}&redirect_uri=${encodedRedirectUri}&response_type=token`;
}
logout() {
const idServiceUri = this.config.get('ID_SERVICE_URL');
localStorage.removeItem('id_token');
window.location.href = idServiceUri + '/users/sign_out';
}
isLoggedIn() {
return tokenNotExpired();
}
parseAuthHash(authHash) {
let re = /access_token=([^&]*)/i;
let found = authHash.match(re);
let token = found[1];
localStorage.setItem('id_token', token);
}
setRedirectUrl(url) {
localStorage.setItem('redirectUrl', url);
}
getRedirectUrl() {
return localStorage.getItem('redirectUrl') || '/';
}
getCurrentUser() {
let token = localStorage.getItem('id_token');
let decodedToken = this.jwtHelper.decodeToken(token);
return decodedToken.user;
}
}
import { Injectable } from '@angular/core';
@Injectable()
export class Config {
private config: any;
constructor() {
this.config = process.env;
}
public get(key: any) {
return this.config[key];
}
}
import { Component, OnInit, OnDestroy, Inject } from '@angular/core';
import { Router } from '@angular/router';
import { AuthService, UserService } from '../../shared';
@Component({
selector: 'navbar',
template: require('./navbar.component.pug'),
styles: [require('./navbar.component.scss')]
})
export class NavbarComponent implements OnInit, OnDestroy {
user: any = null;
sub: any;
constructor(
private router: Router,
private authService: AuthService,
private userService: UserService) { }
ngOnInit() {
this.sub = this.router.events
.subscribe(() => {
this.getCurrentUser();
});
}
ngOnDestroy() {
this.sub.unsubscribe();
}
getCurrentUser() {
if (!this.authService.isLoggedIn() || this.user) { return; }
this.userService.getCurrentUser()
.subscribe(res => {
this.user = res;
});
}
loginClicked() {
this.authService.login();
}
logoutClicked() {
this.user = null;
this.authService.logout();
}
}
import { Injectable } from '@angular/core';
import { Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { AuthHttp } from 'angular2-jwt';
import { Config } from './config';
@Injectable()
export class UserService {
private baseUrl: string = '/users';
constructor(private config: Config, private authHttp: AuthHttp) {
this.baseUrl = this.config.get('API_URL') + this.baseUrl;
}
getCurrentUser(): Observable<any> {
let url = `${this.baseUrl}/current`;
return this.authHttp.get(url)
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
return body.data || { };
}
private handleError(error: any) {
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg);
return Observable.throw(errMsg);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment