├── src ├── assets │ ├── .gitkeep │ └── .npmignore ├── app │ ├── shared │ │ ├── interceptors │ │ │ ├── index.ts │ │ │ └── http.token.interceptor.ts │ │ ├── article-helpers │ │ │ ├── article-list.component.css │ │ │ ├── index.ts │ │ │ ├── article-meta.component.ts │ │ │ ├── article-meta.component.html │ │ │ ├── article-preview.component.ts │ │ │ ├── article-preview.component.html │ │ │ ├── article-list.component.html │ │ │ └── article-list.component.ts │ │ ├── layout │ │ │ ├── index.ts │ │ │ ├── footer.component.ts │ │ │ ├── footer.component.html │ │ │ ├── header.component.ts │ │ │ └── header.component.html │ │ ├── models │ │ │ ├── errors.model.ts │ │ │ ├── profile.model.ts │ │ │ ├── user.model.ts │ │ │ ├── comment.model.ts │ │ │ ├── index.ts │ │ │ ├── article-list-config.model.ts │ │ │ └── article.model.ts │ │ ├── buttons │ │ │ ├── index.ts │ │ │ ├── favorite-button.component.html │ │ │ ├── follow-button.component.html │ │ │ ├── follow-button.component.ts │ │ │ └── favorite-button.component.ts │ │ ├── list-errors.component.html │ │ ├── services │ │ │ ├── index.ts │ │ │ ├── jwt.service.ts │ │ │ ├── tags.service.ts │ │ │ ├── auth-guard.service.ts │ │ │ ├── profiles.service.ts │ │ │ ├── comments.service.ts │ │ │ ├── api.service.ts │ │ │ ├── articles.service.ts │ │ │ └── user.service.ts │ │ ├── index.ts │ │ ├── list-errors.component.ts │ │ ├── show-authed.directive.ts │ │ └── shared.module.ts │ ├── index.ts │ ├── home │ │ ├── home.component.css │ │ ├── home-auth-resolver.service.ts │ │ ├── home.module.ts │ │ ├── home.component.ts │ │ └── home.component.html │ ├── profile │ │ ├── profile-articles.component.html │ │ ├── profile-favorites.component.html │ │ ├── profile-resolver.service.ts │ │ ├── profile-favorites.component.ts │ │ ├── profile-articles.component.ts │ │ ├── profile.component.ts │ │ ├── profile.module.ts │ │ └── profile.component.html │ ├── app.component.html │ ├── article │ │ ├── markdown.pipe.ts │ │ ├── article-comment.component.html │ │ ├── article-resolver.service.ts │ │ ├── article-comment.component.ts │ │ ├── article.module.ts │ │ ├── article.component.ts │ │ └── article.component.html │ ├── app.component.ts │ ├── settings │ │ ├── settings.module.ts │ │ ├── settings.component.ts │ │ └── settings.component.html │ ├── auth │ │ ├── no-auth-guard.service.ts │ │ ├── auth.module.ts │ │ ├── auth.component.html │ │ └── auth.component.ts │ ├── editor │ │ ├── editor.module.ts │ │ ├── editable-article-resolver.service.ts │ │ ├── editor.component.html │ │ └── editor.component.ts │ └── app.module.ts ├── styles.css ├── favicon.ico ├── typings.d.ts ├── environments │ ├── environment.prod.ts │ └── environment.ts ├── tsconfig.app.json ├── tsconfig.spec.json ├── main.ts ├── index.html ├── test.ts └── polyfills.ts ├── logo.png ├── e2e ├── app.po.ts ├── tsconfig.e2e.json └── app.e2e-spec.ts ├── .editorconfig ├── tsconfig.json ├── .gitignore ├── protractor.conf.js ├── karma.conf.js ├── .angular-cli.json ├── package.json ├── tslint.json └── README.md /src/assets/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/assets/.npmignore: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/app/shared/interceptors/index.ts: -------------------------------------------------------------------------------- 1 | export * from './http.token.interceptor'; 2 | -------------------------------------------------------------------------------- /src/app/index.ts: -------------------------------------------------------------------------------- 1 | export * from './app.component'; 2 | export * from './app.module'; 3 | -------------------------------------------------------------------------------- /logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pranesh239/angular-realworld-example-app/master/logo.png -------------------------------------------------------------------------------- /src/styles.css: -------------------------------------------------------------------------------- 1 | /* You can add global styles to this file, and also import other style files */ 2 | -------------------------------------------------------------------------------- /src/app/shared/article-helpers/article-list.component.css: -------------------------------------------------------------------------------- 1 | .page-link { 2 | cursor: pointer; 3 | } 4 | -------------------------------------------------------------------------------- /src/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pranesh239/angular-realworld-example-app/master/src/favicon.ico -------------------------------------------------------------------------------- /src/app/shared/layout/index.ts: -------------------------------------------------------------------------------- 1 | export * from './footer.component'; 2 | export * from './header.component'; 3 | -------------------------------------------------------------------------------- /src/app/shared/models/errors.model.ts: -------------------------------------------------------------------------------- 1 | export interface Errors { 2 | errors: {[key: string]: string}; 3 | } 4 | -------------------------------------------------------------------------------- /src/app/home/home.component.css: -------------------------------------------------------------------------------- 1 | .nav-link { 2 | cursor:pointer; 3 | } 4 | 5 | .tag-pill{ 6 | cursor:pointer; 7 | } 8 | -------------------------------------------------------------------------------- /src/app/shared/buttons/index.ts: -------------------------------------------------------------------------------- 1 | export * from './favorite-button.component'; 2 | export * from './follow-button.component'; 3 | -------------------------------------------------------------------------------- /src/app/profile/profile-articles.component.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /src/app/profile/profile-favorites.component.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /src/typings.d.ts: -------------------------------------------------------------------------------- 1 | /* SystemJS module definition */ 2 | declare var module: NodeModule; 3 | interface NodeModule { 4 | id: string; 5 | } 6 | -------------------------------------------------------------------------------- /src/environments/environment.prod.ts: -------------------------------------------------------------------------------- 1 | export const environment = { 2 | production: true, 3 | api_url: 'https://conduit.productionready.io/api' 4 | }; 5 | -------------------------------------------------------------------------------- /src/app/app.component.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /src/app/shared/models/profile.model.ts: -------------------------------------------------------------------------------- 1 | export interface Profile { 2 | username: string; 3 | bio: string; 4 | image: string; 5 | following: boolean; 6 | } 7 | -------------------------------------------------------------------------------- /src/app/shared/list-errors.component.html: -------------------------------------------------------------------------------- 1 | 6 | -------------------------------------------------------------------------------- /src/app/shared/models/user.model.ts: -------------------------------------------------------------------------------- 1 | export interface User { 2 | email: string; 3 | token: string; 4 | username: string; 5 | bio: string; 6 | image: string; 7 | } 8 | -------------------------------------------------------------------------------- /src/app/shared/article-helpers/index.ts: -------------------------------------------------------------------------------- 1 | export * from './article-list.component'; 2 | export * from './article-meta.component'; 3 | export * from './article-preview.component'; 4 | -------------------------------------------------------------------------------- /src/app/shared/models/comment.model.ts: -------------------------------------------------------------------------------- 1 | import { Profile } from './profile.model'; 2 | 3 | export interface Comment { 4 | id: number; 5 | body: string; 6 | createdAt: string; 7 | author: Profile; 8 | } 9 | -------------------------------------------------------------------------------- /src/app/shared/models/index.ts: -------------------------------------------------------------------------------- 1 | export * from './article.model'; 2 | export * from './article-list-config.model'; 3 | export * from './comment.model'; 4 | export * from './errors.model'; 5 | export * from './profile.model'; 6 | export * from './user.model'; 7 | -------------------------------------------------------------------------------- /e2e/app.po.ts: -------------------------------------------------------------------------------- 1 | import { browser, element, by } from 'protractor'; 2 | 3 | export class Ng2RealApp { 4 | navigateTo() { 5 | return browser.get('/'); 6 | } 7 | 8 | getParagraphText() { 9 | return element(by.css('.logo-font')).getText(); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/app/shared/models/article-list-config.model.ts: -------------------------------------------------------------------------------- 1 | export interface ArticleListConfig { 2 | type: string; 3 | 4 | filters: { 5 | tag?: string, 6 | author?: string, 7 | favorited?: string, 8 | limit?: number, 9 | offset?: number 10 | }; 11 | } 12 | -------------------------------------------------------------------------------- /src/app/shared/layout/footer.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | 3 | @Component({ 4 | selector: 'app-layout-footer', 5 | templateUrl: './footer.component.html' 6 | }) 7 | export class FooterComponent { 8 | today: number = Date.now(); 9 | } 10 | -------------------------------------------------------------------------------- /src/tsconfig.app.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/app", 5 | "baseUrl": "./", 6 | "module": "es2015", 7 | "types": [] 8 | }, 9 | "exclude": [ 10 | "test.ts", 11 | "**/*.spec.ts" 12 | ] 13 | } 14 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # Editor configuration, see http://editorconfig.org 2 | root = true 3 | 4 | [*] 5 | charset = utf-8 6 | indent_style = space 7 | indent_size = 2 8 | insert_final_newline = true 9 | trim_trailing_whitespace = true 10 | 11 | [*.md] 12 | max_line_length = off 13 | trim_trailing_whitespace = false 14 | -------------------------------------------------------------------------------- /e2e/tsconfig.e2e.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/e2e", 5 | "baseUrl": "./", 6 | "module": "commonjs", 7 | "target": "es5", 8 | "types": [ 9 | "jasmine", 10 | "jasminewd2", 11 | "node" 12 | ] 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/app/article/markdown.pipe.ts: -------------------------------------------------------------------------------- 1 | import { Pipe, PipeTransform } from '@angular/core'; 2 | import * as marked from 'marked'; 3 | 4 | @Pipe({name: 'markdown'}) 5 | export class MarkdownPipe implements PipeTransform { 6 | transform(content: string): string { 7 | return marked(content, { sanitize: true }); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/app/shared/services/index.ts: -------------------------------------------------------------------------------- 1 | export * from './api.service'; 2 | export * from './articles.service'; 3 | export * from './auth-guard.service'; 4 | export * from './comments.service'; 5 | export * from './jwt.service'; 6 | export * from './profiles.service'; 7 | export * from './tags.service'; 8 | export * from './user.service'; 9 | -------------------------------------------------------------------------------- /src/app/shared/buttons/favorite-button.component.html: -------------------------------------------------------------------------------- 1 | 8 | -------------------------------------------------------------------------------- /src/app/shared/index.ts: -------------------------------------------------------------------------------- 1 | export * from './article-helpers'; 2 | export * from './buttons'; 3 | export * from './layout'; 4 | export * from './list-errors.component'; 5 | export * from './models'; 6 | export * from './services'; 7 | export * from './shared.module'; 8 | export * from './show-authed.directive'; 9 | export * from './interceptors'; 10 | -------------------------------------------------------------------------------- /src/app/shared/article-helpers/article-meta.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, Input } from '@angular/core'; 2 | 3 | import { Article } from '../models'; 4 | 5 | @Component({ 6 | selector: 'app-article-meta', 7 | templateUrl: './article-meta.component.html' 8 | }) 9 | export class ArticleMetaComponent { 10 | @Input() article: Article; 11 | } 12 | -------------------------------------------------------------------------------- /src/app/shared/models/article.model.ts: -------------------------------------------------------------------------------- 1 | import { Profile } from './profile.model'; 2 | 3 | export interface Article { 4 | slug: string; 5 | title: string; 6 | description: string; 7 | body: string; 8 | tagList: string[]; 9 | createdAt: string; 10 | updatedAt: string; 11 | favorited: boolean; 12 | favoritesCount: number; 13 | author: Profile; 14 | } 15 | -------------------------------------------------------------------------------- /e2e/app.e2e-spec.ts: -------------------------------------------------------------------------------- 1 | import { Ng2RealApp } from './app.po'; 2 | 3 | describe('ng-demo App', () => { 4 | let page: Ng2RealApp; 5 | 6 | beforeEach(() => { 7 | page = new Ng2RealApp(); 8 | }); 9 | 10 | it('should display message saying app works', () => { 11 | page.navigateTo(); 12 | expect(page.getParagraphText()).toContain('conduit'); 13 | }); 14 | }); 15 | -------------------------------------------------------------------------------- /src/app/shared/layout/footer.component.html: -------------------------------------------------------------------------------- 1 | 11 | -------------------------------------------------------------------------------- /src/tsconfig.spec.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/spec", 5 | "baseUrl": "./", 6 | "module": "commonjs", 7 | "target": "es5", 8 | "types": [ 9 | "jasmine", 10 | "node" 11 | ] 12 | }, 13 | "files": [ 14 | "test.ts" 15 | ], 16 | "include": [ 17 | "**/*.spec.ts", 18 | "**/*.d.ts" 19 | ] 20 | } 21 | -------------------------------------------------------------------------------- /src/app/app.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | 3 | import { UserService } from './shared'; 4 | 5 | @Component({ 6 | selector: 'app-root', 7 | templateUrl: './app.component.html' 8 | }) 9 | export class AppComponent implements OnInit { 10 | constructor ( 11 | private userService: UserService 12 | ) {} 13 | 14 | ngOnInit() { 15 | this.userService.populate(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/app/shared/services/jwt.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | 3 | 4 | @Injectable() 5 | export class JwtService { 6 | 7 | getToken(): String { 8 | return window.localStorage['jwtToken']; 9 | } 10 | 11 | saveToken(token: String) { 12 | window.localStorage['jwtToken'] = token; 13 | } 14 | 15 | destroyToken() { 16 | window.localStorage.removeItem('jwtToken'); 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/app/shared/buttons/follow-button.component.html: -------------------------------------------------------------------------------- 1 | 11 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compileOnSave": false, 3 | "compilerOptions": { 4 | "outDir": "./dist/out-tsc", 5 | "sourceMap": true, 6 | "declaration": false, 7 | "moduleResolution": "node", 8 | "emitDecoratorMetadata": true, 9 | "experimentalDecorators": true, 10 | "target": "es5", 11 | "typeRoots": [ 12 | "node_modules/@types" 13 | ], 14 | "lib": [ 15 | "es2017", 16 | "dom" 17 | ] 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/environments/environment.ts: -------------------------------------------------------------------------------- 1 | // The file contents for the current environment will overwrite these during build. 2 | // The build system defaults to the dev environment which uses `environment.ts`, but if you do 3 | // `ng build --env=prod` then `environment.prod.ts` will be used instead. 4 | // The list of which env maps to which file can be found in `angular-cli.json`. 5 | 6 | export const environment = { 7 | production: false, 8 | api_url: 'https://conduit.productionready.io/api' 9 | }; 10 | -------------------------------------------------------------------------------- /src/app/shared/services/tags.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { Observable } from 'rxjs/Observable'; 3 | 4 | import { ApiService } from './api.service'; 5 | import { map } from 'rxjs/operators'; 6 | 7 | @Injectable() 8 | export class TagsService { 9 | constructor ( 10 | private apiService: ApiService 11 | ) {} 12 | 13 | getAll(): Observable<[string]> { 14 | return this.apiService.get('/tags') 15 | .pipe(map(data => data.tags)); 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /src/app/shared/article-helpers/article-meta.component.html: -------------------------------------------------------------------------------- 1 |
2 | 3 | 4 | 5 | 6 |
7 | 9 | {{ article.author.username }} 10 | 11 | 12 | {{ article.createdAt | date: 'longDate' }} 13 | 14 |
15 | 16 | 17 |
18 | -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | import { enableProdMode } from '@angular/core'; 2 | import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; 3 | 4 | import { AppModule } from './app/app.module'; 5 | import { environment } from './environments/environment'; 6 | 7 | if (environment.production) { 8 | enableProdMode(); 9 | } 10 | 11 | const bootstrapPromise = platformBrowserDynamic().bootstrapModule(AppModule); 12 | 13 | // Logging bootstrap information 14 | bootstrapPromise.then(success => console.log(`Bootstrap success`)) 15 | .catch(err => console.error(err)); 16 | -------------------------------------------------------------------------------- /src/app/shared/list-errors.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, Input } from '@angular/core'; 2 | 3 | import { Errors } from './models'; 4 | 5 | @Component({ 6 | selector: 'app-list-errors', 7 | templateUrl: './list-errors.component.html' 8 | }) 9 | export class ListErrorsComponent { 10 | formattedErrors: Array = []; 11 | 12 | @Input() 13 | set errors(errorList: Errors) { 14 | this.formattedErrors = Object.keys(errorList.errors || {}) 15 | .map(key => `${key} ${errorList.errors[key]}`); 16 | } 17 | 18 | get errorList() { return this.formattedErrors; } 19 | 20 | 21 | } 22 | -------------------------------------------------------------------------------- /src/app/shared/article-helpers/article-preview.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, Input } from '@angular/core'; 2 | 3 | import { Article } from '../models'; 4 | 5 | @Component({ 6 | selector: 'app-article-preview', 7 | templateUrl: './article-preview.component.html' 8 | }) 9 | export class ArticlePreviewComponent { 10 | @Input() article: Article; 11 | 12 | onToggleFavorite(favorited: boolean) { 13 | this.article['favorited'] = favorited; 14 | 15 | if (favorited) { 16 | this.article['favoritesCount']++; 17 | } else { 18 | this.article['favoritesCount']--; 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/app/shared/layout/header.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | 3 | import { User } from '../models'; 4 | import { UserService } from '../services'; 5 | 6 | @Component({ 7 | selector: 'app-layout-header', 8 | templateUrl: './header.component.html' 9 | }) 10 | export class HeaderComponent implements OnInit { 11 | constructor( 12 | private userService: UserService 13 | ) {} 14 | 15 | currentUser: User; 16 | 17 | ngOnInit() { 18 | this.userService.currentUser.subscribe( 19 | (userData) => { 20 | this.currentUser = userData; 21 | } 22 | ); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/app/settings/settings.module.ts: -------------------------------------------------------------------------------- 1 | import { ModuleWithProviders, NgModule } from '@angular/core'; 2 | import { RouterModule } from '@angular/router'; 3 | 4 | import { SettingsComponent } from './settings.component'; 5 | import { AuthGuard, SharedModule } from '../shared'; 6 | 7 | const settingsRouting: ModuleWithProviders = RouterModule.forChild([ 8 | { 9 | path: 'settings', 10 | component: SettingsComponent, 11 | canActivate: [AuthGuard] 12 | } 13 | ]); 14 | 15 | @NgModule({ 16 | imports: [ 17 | SharedModule, 18 | settingsRouting 19 | ], 20 | declarations: [ 21 | SettingsComponent 22 | ] 23 | }) 24 | export class SettingsModule {} 25 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See http://help.github.com/ignore-files/ for more about ignoring files. 2 | 3 | # compiled output 4 | /dist 5 | /tmp 6 | /out-tsc 7 | 8 | # dependencies 9 | /node_modules 10 | 11 | # IDEs and editors 12 | /.idea 13 | .project 14 | .classpath 15 | .c9/ 16 | *.launch 17 | .settings/ 18 | *.sublime-workspace 19 | 20 | # IDE - VSCode 21 | .vscode/* 22 | !.vscode/settings.json 23 | !.vscode/tasks.json 24 | !.vscode/launch.json 25 | !.vscode/extensions.json 26 | 27 | # misc 28 | /.sass-cache 29 | /connect.lock 30 | /coverage 31 | /libpeerconnection.log 32 | npm-debug.log 33 | testem.log 34 | /typings 35 | 36 | # e2e 37 | /e2e/*.js 38 | /e2e/*.map 39 | 40 | # System Files 41 | .DS_Store 42 | Thumbs.db 43 | -------------------------------------------------------------------------------- /src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Conduit 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | Loading... 16 | 17 | 18 | -------------------------------------------------------------------------------- /src/app/home/home-auth-resolver.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { ActivatedRouteSnapshot, Resolve, Router, RouterStateSnapshot } from '@angular/router'; 3 | import { Observable } from 'rxjs/Observable'; 4 | 5 | import { UserService } from '../shared'; 6 | import { take } from 'rxjs/operators'; 7 | 8 | @Injectable() 9 | export class HomeAuthResolver implements Resolve { 10 | constructor( 11 | private router: Router, 12 | private userService: UserService 13 | ) {} 14 | 15 | resolve( 16 | route: ActivatedRouteSnapshot, 17 | state: RouterStateSnapshot 18 | ): Observable { 19 | 20 | return this.userService.isAuthenticated.pipe(take(1)); 21 | 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/app/shared/services/auth-guard.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot } from '@angular/router'; 3 | import { Observable } from 'rxjs/Observable'; 4 | 5 | import { UserService } from './user.service'; 6 | import { take } from 'rxjs/operators'; 7 | 8 | @Injectable() 9 | export class AuthGuard implements CanActivate { 10 | constructor( 11 | private router: Router, 12 | private userService: UserService 13 | ) {} 14 | 15 | canActivate( 16 | route: ActivatedRouteSnapshot, 17 | state: RouterStateSnapshot 18 | ): Observable { 19 | 20 | return this.userService.isAuthenticated.pipe(take(1)); 21 | 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/app/auth/no-auth-guard.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot } from '@angular/router'; 3 | import { Observable } from 'rxjs/Observable'; 4 | 5 | import { UserService } from '../shared'; 6 | import { take, map } from 'rxjs/operators'; 7 | 8 | @Injectable() 9 | export class NoAuthGuard implements CanActivate { 10 | constructor( 11 | private router: Router, 12 | private userService: UserService 13 | ) {} 14 | 15 | canActivate( 16 | route: ActivatedRouteSnapshot, 17 | state: RouterStateSnapshot 18 | ): Observable { 19 | 20 | return this.userService.isAuthenticated.pipe(take(1), map(isAuth => !isAuth)); 21 | 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/app/shared/article-helpers/article-preview.component.html: -------------------------------------------------------------------------------- 1 |
2 | 3 | 7 | {{article.favoritesCount}} 8 | 9 | 10 | 11 | 12 |

{{ article.title }}

13 |

{{ article.description }}

14 | Read more... 15 |
    16 |
  • 18 | {{ tag }} 19 |
  • 20 |
21 |
22 |
23 | -------------------------------------------------------------------------------- /src/app/home/home.module.ts: -------------------------------------------------------------------------------- 1 | import { ModuleWithProviders, NgModule } from '@angular/core'; 2 | import { RouterModule } from '@angular/router'; 3 | 4 | import { HomeComponent } from './home.component'; 5 | import { HomeAuthResolver } from './home-auth-resolver.service'; 6 | import { SharedModule } from '../shared'; 7 | 8 | const homeRouting: ModuleWithProviders = RouterModule.forChild([ 9 | { 10 | path: '', 11 | component: HomeComponent, 12 | resolve: { 13 | isAuthenticated: HomeAuthResolver 14 | } 15 | } 16 | ]); 17 | 18 | @NgModule({ 19 | imports: [ 20 | homeRouting, 21 | SharedModule 22 | ], 23 | declarations: [ 24 | HomeComponent 25 | ], 26 | providers: [ 27 | HomeAuthResolver 28 | ] 29 | }) 30 | export class HomeModule {} 31 | -------------------------------------------------------------------------------- /src/app/shared/article-helpers/article-list.component.html: -------------------------------------------------------------------------------- 1 | 4 | 5 | 6 |
8 | Loading articles... 9 |
10 | 11 |
13 | No articles are here... yet. 14 |
15 | 16 | 30 | -------------------------------------------------------------------------------- /src/app/article/article-comment.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 |

4 | {{ comment.body }} 5 |

6 |
7 | 22 |
23 | -------------------------------------------------------------------------------- /src/app/profile/profile-resolver.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable, } from '@angular/core'; 2 | import { ActivatedRouteSnapshot, Resolve, Router, RouterStateSnapshot } from '@angular/router'; 3 | import { Observable } from 'rxjs/Observable'; 4 | 5 | import { Profile, ProfilesService } from '../shared'; 6 | import { catchError } from 'rxjs/operators'; 7 | 8 | @Injectable() 9 | export class ProfileResolver implements Resolve { 10 | constructor( 11 | private profilesService: ProfilesService, 12 | private router: Router 13 | ) {} 14 | 15 | resolve( 16 | route: ActivatedRouteSnapshot, 17 | state: RouterStateSnapshot 18 | ): Observable { 19 | 20 | return this.profilesService.get(route.params['username']) 21 | .pipe(catchError((err) => this.router.navigateByUrl('/'))); 22 | 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /protractor.conf.js: -------------------------------------------------------------------------------- 1 | // Protractor configuration file, see link for more information 2 | // https://github.com/angular/protractor/blob/master/lib/config.ts 3 | 4 | const { SpecReporter } = require('jasmine-spec-reporter'); 5 | 6 | exports.config = { 7 | allScriptsTimeout: 11000, 8 | specs: [ 9 | './e2e/**/*.e2e-spec.ts' 10 | ], 11 | capabilities: { 12 | 'browserName': 'chrome' 13 | }, 14 | directConnect: true, 15 | baseUrl: 'http://localhost:4200/', 16 | framework: 'jasmine', 17 | jasmineNodeOpts: { 18 | showColors: true, 19 | defaultTimeoutInterval: 30000, 20 | print: function() {} 21 | }, 22 | onPrepare() { 23 | require('ts-node').register({ 24 | project: 'e2e/tsconfig.e2e.json' 25 | }); 26 | jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } })); 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /src/app/auth/auth.module.ts: -------------------------------------------------------------------------------- 1 | import { ModuleWithProviders, NgModule } from '@angular/core'; 2 | import { RouterModule } from '@angular/router'; 3 | 4 | import { AuthComponent } from './auth.component'; 5 | import { NoAuthGuard } from './no-auth-guard.service'; 6 | import { SharedModule } from '../shared'; 7 | 8 | const authRouting: ModuleWithProviders = RouterModule.forChild([ 9 | { 10 | path: 'login', 11 | component: AuthComponent, 12 | canActivate: [NoAuthGuard] 13 | }, 14 | { 15 | path: 'register', 16 | component: AuthComponent, 17 | canActivate: [NoAuthGuard] 18 | } 19 | ]); 20 | 21 | @NgModule({ 22 | imports: [ 23 | authRouting, 24 | SharedModule 25 | ], 26 | declarations: [ 27 | AuthComponent 28 | ], 29 | 30 | providers: [ 31 | NoAuthGuard 32 | ] 33 | }) 34 | export class AuthModule {} 35 | -------------------------------------------------------------------------------- /src/app/article/article-resolver.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable, } from '@angular/core'; 2 | import { ActivatedRouteSnapshot, Resolve, Router, RouterStateSnapshot } from '@angular/router'; 3 | import { Observable } from 'rxjs/Observable'; 4 | 5 | import { Article, ArticlesService, UserService } from '../shared'; 6 | import { catchError } from 'rxjs/operators'; 7 | 8 | @Injectable() 9 | export class ArticleResolver implements Resolve
{ 10 | constructor( 11 | private articlesService: ArticlesService, 12 | private router: Router, 13 | private userService: UserService 14 | ) {} 15 | 16 | resolve( 17 | route: ActivatedRouteSnapshot, 18 | state: RouterStateSnapshot 19 | ): Observable { 20 | 21 | return this.articlesService.get(route.params['slug']) 22 | .pipe(catchError((err) => this.router.navigateByUrl('/'))); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/app/shared/services/profiles.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { Observable } from 'rxjs/Observable'; 3 | 4 | import { ApiService } from './api.service'; 5 | import { Profile } from '../models'; 6 | import { map } from 'rxjs/operators/map'; 7 | 8 | @Injectable() 9 | export class ProfilesService { 10 | constructor ( 11 | private apiService: ApiService 12 | ) {} 13 | 14 | get(username: string): Observable { 15 | return this.apiService.get('/profiles/' + username) 16 | .pipe(map((data: {profile: Profile}) => data.profile)); 17 | } 18 | 19 | follow(username: string): Observable { 20 | return this.apiService.post('/profiles/' + username + '/follow'); 21 | } 22 | 23 | unfollow(username: string): Observable { 24 | return this.apiService.delete('/profiles/' + username + '/follow'); 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/app/profile/profile-favorites.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { ActivatedRoute, Router } from '@angular/router'; 3 | 4 | import { ArticleListConfig, Profile } from '../shared'; 5 | 6 | @Component({ 7 | selector: 'app-profile-favorites', 8 | templateUrl: './profile-favorites.component.html' 9 | }) 10 | export class ProfileFavoritesComponent implements OnInit { 11 | constructor( 12 | private route: ActivatedRoute, 13 | private router: Router 14 | ) {} 15 | 16 | profile: Profile; 17 | favoritesConfig: ArticleListConfig = { 18 | type: 'all', 19 | filters: {} 20 | }; 21 | 22 | ngOnInit() { 23 | this.route.parent.data.subscribe( 24 | (data: {profile: Profile}) => { 25 | this.profile = data.profile; 26 | this.favoritesConfig.filters.favorited = this.profile.username; 27 | } 28 | ); 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/app/article/article-comment.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, EventEmitter, Input, Output, OnInit } from '@angular/core'; 2 | 3 | import { Comment, User, UserService } from '../shared'; 4 | 5 | @Component({ 6 | selector: 'app-article-comment', 7 | templateUrl: './article-comment.component.html' 8 | }) 9 | export class ArticleCommentComponent implements OnInit { 10 | constructor( 11 | private userService: UserService 12 | ) {} 13 | 14 | @Input() comment: Comment; 15 | @Output() deleteComment = new EventEmitter(); 16 | 17 | canModify: boolean; 18 | 19 | ngOnInit() { 20 | // Load the current user's data 21 | this.userService.currentUser.subscribe( 22 | (userData: User) => { 23 | this.canModify = (userData.username === this.comment.author.username); 24 | } 25 | ); 26 | } 27 | 28 | deleteClicked() { 29 | this.deleteComment.emit(true); 30 | } 31 | 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/app/shared/interceptors/http.token.interceptor.ts: -------------------------------------------------------------------------------- 1 | import { Injectable, Injector } from '@angular/core'; 2 | import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http'; 3 | import { Observable } from 'rxjs/Observable'; 4 | 5 | import { JwtService } from '../services'; 6 | 7 | @Injectable() 8 | export class HttpTokenInterceptor implements HttpInterceptor { 9 | constructor(private jwtService: JwtService) {} 10 | 11 | intercept(req: HttpRequest, next: HttpHandler): Observable> { 12 | const headersConfig = { 13 | 'Content-Type': 'application/json', 14 | 'Accept': 'application/json' 15 | }; 16 | 17 | const token = this.jwtService.getToken(); 18 | 19 | if (token) { 20 | headersConfig['Authorization'] = `Token ${token}`; 21 | const authReq = req.clone({ setHeaders: headersConfig }); 22 | return next.handle(authReq); 23 | } 24 | return next.handle(req); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/app/shared/services/comments.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { Observable } from 'rxjs/Observable'; 3 | 4 | import { ApiService } from './api.service'; 5 | import { Comment } from '../models'; 6 | import { map } from 'rxjs/operators'; 7 | 8 | 9 | @Injectable() 10 | export class CommentsService { 11 | constructor ( 12 | private apiService: ApiService 13 | ) {} 14 | 15 | add(slug, payload): Observable { 16 | return this.apiService 17 | .post( 18 | `/articles/${slug}/comments`, 19 | { comment: { body: payload } } 20 | ).pipe(map(data => data.comment)); 21 | } 22 | 23 | getAll(slug): Observable { 24 | return this.apiService.get(`/articles/${slug}/comments`) 25 | .pipe(map(data => data.comments)); 26 | } 27 | 28 | destroy(commentId, articleSlug) { 29 | return this.apiService 30 | .delete(`/articles/${articleSlug}/comments/${commentId}`); 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/app/editor/editor.module.ts: -------------------------------------------------------------------------------- 1 | import { ModuleWithProviders, NgModule } from '@angular/core'; 2 | import { RouterModule } from '@angular/router'; 3 | 4 | import { EditorComponent } from './editor.component'; 5 | import { EditableArticleResolver } from './editable-article-resolver.service'; 6 | import { AuthGuard, SharedModule } from '../shared'; 7 | 8 | const editorRouting: ModuleWithProviders = RouterModule.forChild([ 9 | { 10 | path: 'editor', 11 | component: EditorComponent, 12 | canActivate: [AuthGuard] 13 | }, 14 | { 15 | path: 'editor/:slug', 16 | component: EditorComponent, 17 | canActivate: [AuthGuard], 18 | resolve: { 19 | article: EditableArticleResolver 20 | } 21 | } 22 | ]); 23 | 24 | @NgModule({ 25 | imports: [ 26 | editorRouting, 27 | SharedModule 28 | ], 29 | declarations: [ 30 | EditorComponent 31 | ], 32 | providers: [ 33 | EditableArticleResolver 34 | ] 35 | }) 36 | export class EditorModule {} 37 | -------------------------------------------------------------------------------- /src/app/article/article.module.ts: -------------------------------------------------------------------------------- 1 | import { ModuleWithProviders, NgModule } from '@angular/core'; 2 | import { RouterModule } from '@angular/router'; 3 | 4 | import { ArticleComponent } from './article.component'; 5 | import { ArticleCommentComponent } from './article-comment.component'; 6 | import { ArticleResolver } from './article-resolver.service'; 7 | import { MarkdownPipe } from './markdown.pipe'; 8 | import { SharedModule } from '../shared'; 9 | 10 | const articleRouting: ModuleWithProviders = RouterModule.forChild([ 11 | { 12 | path: 'article/:slug', 13 | component: ArticleComponent, 14 | resolve: { 15 | article: ArticleResolver 16 | } 17 | } 18 | ]); 19 | 20 | @NgModule({ 21 | imports: [ 22 | articleRouting, 23 | SharedModule 24 | ], 25 | declarations: [ 26 | ArticleComponent, 27 | ArticleCommentComponent, 28 | MarkdownPipe 29 | ], 30 | 31 | providers: [ 32 | ArticleResolver 33 | ] 34 | }) 35 | export class ArticleModule {} 36 | -------------------------------------------------------------------------------- /src/app/shared/show-authed.directive.ts: -------------------------------------------------------------------------------- 1 | import { 2 | Directive, 3 | Input, 4 | OnInit, 5 | TemplateRef, 6 | ViewContainerRef 7 | } from '@angular/core'; 8 | 9 | import { UserService } from './services/user.service'; 10 | 11 | @Directive({ selector: '[showAuthed]' }) 12 | export class ShowAuthedDirective implements OnInit { 13 | constructor( 14 | private templateRef: TemplateRef, 15 | private userService: UserService, 16 | private viewContainer: ViewContainerRef 17 | ) {} 18 | 19 | condition: boolean; 20 | 21 | ngOnInit() { 22 | this.userService.isAuthenticated.subscribe( 23 | (isAuthenticated) => { 24 | if (isAuthenticated && this.condition || !isAuthenticated && !this.condition) { 25 | this.viewContainer.createEmbeddedView(this.templateRef); 26 | } else { 27 | this.viewContainer.clear(); 28 | } 29 | } 30 | ); 31 | } 32 | 33 | @Input() set showAuthed(condition: boolean) { 34 | this.condition = condition; 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /src/app/profile/profile-articles.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { ActivatedRoute, Router } from '@angular/router'; 3 | 4 | import { ArticleListConfig, Profile } from '../shared'; 5 | 6 | @Component({ 7 | selector: 'app-profile-articles', 8 | templateUrl: './profile-articles.component.html' 9 | }) 10 | export class ProfileArticlesComponent implements OnInit { 11 | constructor( 12 | private route: ActivatedRoute, 13 | private router: Router 14 | ) {} 15 | 16 | profile: Profile; 17 | articlesConfig: ArticleListConfig = { 18 | type: 'all', 19 | filters: {} 20 | }; 21 | 22 | ngOnInit() { 23 | this.route.parent.data.subscribe( 24 | (data: {profile: Profile}) => { 25 | this.profile = data.profile; 26 | this.articlesConfig = { 27 | type: 'all', 28 | filters: {} 29 | }; // Only method I found to refresh article load on swap 30 | this.articlesConfig.filters.author = this.profile.username; 31 | } 32 | ); 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /karma.conf.js: -------------------------------------------------------------------------------- 1 | // Karma configuration file, see link for more information 2 | // https://karma-runner.github.io/1.0/config/configuration-file.html 3 | 4 | module.exports = function(config) { 5 | config.set({ 6 | basePath: '', 7 | frameworks: ['jasmine', '@angular/cli'], 8 | plugins: [ 9 | require('karma-jasmine'), 10 | require('karma-chrome-launcher'), 11 | require('karma-jasmine-html-reporter'), 12 | require('karma-coverage-istanbul-reporter'), 13 | require('@angular/cli/plugins/karma') 14 | ], 15 | client: { 16 | clearContext: false // leave Jasmine Spec Runner output visible in browser 17 | }, 18 | coverageIstanbulReporter: { 19 | reports: ['html', 'lcovonly'], 20 | fixWebpackSourcePaths: true 21 | }, 22 | angularCli: { 23 | environment: 'dev' 24 | }, 25 | reporters: 26 | config.angularCli && config.angularCli.codeCoverage 27 | ? ['progress', 'coverage-istanbul'] 28 | : ['progress', 'kjhtml'], 29 | port: 9876, 30 | colors: true, 31 | logLevel: config.LOG_INFO, 32 | autoWatch: true, 33 | browsers: ['Chrome'], 34 | singleRun: false 35 | }); 36 | }; 37 | -------------------------------------------------------------------------------- /src/app/profile/profile.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { ActivatedRoute } from '@angular/router'; 3 | 4 | import { User, UserService, Profile } from '../shared'; 5 | 6 | @Component({ 7 | selector: 'app-profile-page', 8 | templateUrl: './profile.component.html' 9 | }) 10 | export class ProfileComponent implements OnInit { 11 | constructor( 12 | private route: ActivatedRoute, 13 | private userService: UserService 14 | ) {} 15 | 16 | profile: Profile; 17 | currentUser: User; 18 | isUser: boolean; 19 | 20 | ngOnInit() { 21 | //TODO: mergeMap here 22 | this.route.data.subscribe( 23 | (data: {profile: Profile}) => { 24 | this.profile = data.profile; 25 | // Load the current user's data. 26 | this.userService.currentUser.subscribe( 27 | (userData: User) => { 28 | this.currentUser = userData; 29 | this.isUser = (this.currentUser.username === this.profile.username); 30 | } 31 | ); 32 | } 33 | ); 34 | 35 | 36 | 37 | } 38 | 39 | onToggleFollowing(following: boolean) { 40 | this.profile.following = following; 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /src/app/editor/editable-article-resolver.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { ActivatedRouteSnapshot, Resolve, Router, RouterStateSnapshot } from '@angular/router'; 3 | import { Observable } from 'rxjs/Observable'; 4 | 5 | import { Article, ArticlesService, UserService } from '../shared'; 6 | import { map, catchError } from 'rxjs/operators'; 7 | 8 | @Injectable() 9 | export class EditableArticleResolver implements Resolve
{ 10 | constructor( 11 | private articlesService: ArticlesService, 12 | private router: Router, 13 | private userService: UserService 14 | ) { } 15 | 16 | resolve( 17 | route: ActivatedRouteSnapshot, 18 | state: RouterStateSnapshot 19 | ): Observable { 20 | 21 | return this.articlesService.get(route.params['slug']) 22 | .pipe( 23 | map( 24 | article => { 25 | if (this.userService.getCurrentUser().username === article.author.username) { 26 | return article; 27 | } else { 28 | this.router.navigateByUrl('/'); 29 | } 30 | } 31 | ), 32 | catchError((err) => this.router.navigateByUrl('/')) 33 | ); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/test.ts: -------------------------------------------------------------------------------- 1 | // This file is required by karma.conf.js and loads recursively all the .spec and framework files 2 | 3 | import 'zone.js/dist/long-stack-trace-zone'; 4 | import 'zone.js/dist/proxy.js'; 5 | import 'zone.js/dist/sync-test'; 6 | import 'zone.js/dist/jasmine-patch'; 7 | import 'zone.js/dist/async-test'; 8 | import 'zone.js/dist/fake-async-test'; 9 | import { getTestBed } from '@angular/core/testing'; 10 | import { 11 | BrowserDynamicTestingModule, 12 | platformBrowserDynamicTesting 13 | } from '@angular/platform-browser-dynamic/testing'; 14 | 15 | // Unfortunately there's no typing for the `__karma__` variable. Just declare it as any. 16 | declare const __karma__: any; 17 | declare const require: any; 18 | 19 | // Prevent Karma from running prematurely. 20 | __karma__.loaded = function () {}; 21 | 22 | // First, initialize the Angular testing environment. 23 | getTestBed().initTestEnvironment( 24 | BrowserDynamicTestingModule, 25 | platformBrowserDynamicTesting() 26 | ); 27 | // Then we find all the tests. 28 | const context = require.context('./', true, /\.spec\.ts$/); 29 | // And load the modules. 30 | context.keys().map(context); 31 | // Finally, start Karma to run the tests. 32 | __karma__.start(); 33 | -------------------------------------------------------------------------------- /src/app/profile/profile.module.ts: -------------------------------------------------------------------------------- 1 | import { ModuleWithProviders, NgModule } from '@angular/core'; 2 | import { RouterModule } from '@angular/router'; 3 | 4 | import { ProfileArticlesComponent } from './profile-articles.component'; 5 | import { ProfileComponent } from './profile.component'; 6 | import { ProfileFavoritesComponent } from './profile-favorites.component'; 7 | import { ProfileResolver } from './profile-resolver.service'; 8 | import { SharedModule } from '../shared'; 9 | 10 | const profileRouting: ModuleWithProviders = RouterModule.forChild([ 11 | { 12 | path: 'profile/:username', 13 | component: ProfileComponent, 14 | resolve: { 15 | profile: ProfileResolver 16 | }, 17 | children: [ 18 | { 19 | path: '', 20 | component: ProfileArticlesComponent 21 | }, 22 | { 23 | path: 'favorites', 24 | component: ProfileFavoritesComponent 25 | } 26 | ] 27 | } 28 | ]); 29 | 30 | @NgModule({ 31 | imports: [ 32 | profileRouting, 33 | SharedModule 34 | ], 35 | declarations: [ 36 | ProfileArticlesComponent, 37 | ProfileComponent, 38 | ProfileFavoritesComponent 39 | ], 40 | 41 | providers: [ 42 | ProfileResolver 43 | ] 44 | }) 45 | export class ProfileModule {} 46 | -------------------------------------------------------------------------------- /src/app/shared/shared.module.ts: -------------------------------------------------------------------------------- 1 | import { CommonModule } from '@angular/common'; 2 | import { NgModule } from '@angular/core'; 3 | import { FormsModule, ReactiveFormsModule } from '@angular/forms'; 4 | import { HttpClientModule } from '@angular/common/http'; 5 | import { RouterModule } from '@angular/router'; 6 | 7 | import { ArticleListComponent, ArticleMetaComponent, ArticlePreviewComponent } from './article-helpers'; 8 | import { FavoriteButtonComponent, FollowButtonComponent } from './buttons'; 9 | import { ListErrorsComponent } from './list-errors.component'; 10 | import { ShowAuthedDirective } from './show-authed.directive'; 11 | 12 | @NgModule({ 13 | imports: [ 14 | CommonModule, 15 | FormsModule, 16 | ReactiveFormsModule, 17 | HttpClientModule, 18 | RouterModule 19 | ], 20 | declarations: [ 21 | ArticleListComponent, 22 | ArticleMetaComponent, 23 | ArticlePreviewComponent, 24 | FavoriteButtonComponent, 25 | FollowButtonComponent, 26 | ListErrorsComponent, 27 | ShowAuthedDirective 28 | ], 29 | exports: [ 30 | ArticleListComponent, 31 | ArticleMetaComponent, 32 | ArticlePreviewComponent, 33 | CommonModule, 34 | FavoriteButtonComponent, 35 | FollowButtonComponent, 36 | FormsModule, 37 | ReactiveFormsModule, 38 | HttpClientModule, 39 | ListErrorsComponent, 40 | RouterModule, 41 | ShowAuthedDirective 42 | ] 43 | }) 44 | export class SharedModule {} 45 | -------------------------------------------------------------------------------- /.angular-cli.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "./node_modules/@angular/cli/lib/config/schema.json", 3 | "project": { 4 | "name": "ang2-conduit" 5 | }, 6 | "apps": [ 7 | { 8 | "root": "src", 9 | "outDir": "dist", 10 | "assets": ["assets", "favicon.ico"], 11 | "index": "index.html", 12 | "main": "main.ts", 13 | "polyfills": "polyfills.ts", 14 | "test": "test.ts", 15 | "tsconfig": "tsconfig.app.json", 16 | "testTsconfig": "tsconfig.spec.json", 17 | "prefix": "app", 18 | "styles": ["styles.css"], 19 | "scripts": [], 20 | "environmentSource": "environments/environment.ts", 21 | "environments": { 22 | "dev": "environments/environment.ts", 23 | "prod": "environments/environment.prod.ts" 24 | } 25 | } 26 | ], 27 | "e2e": { 28 | "protractor": { 29 | "config": "./protractor.conf.js" 30 | } 31 | }, 32 | "lint": [ 33 | { 34 | "project": "src/tsconfig.app.json", 35 | "exclude": "**/node_modules/**" 36 | }, 37 | { 38 | "project": "src/tsconfig.spec.json", 39 | "exclude": "**/node_modules/**" 40 | }, 41 | { 42 | "project": "e2e/tsconfig.e2e.json", 43 | "exclude": "**/node_modules/**" 44 | } 45 | ], 46 | "test": { 47 | "karma": { 48 | "config": "./karma.conf.js" 49 | } 50 | }, 51 | "defaults": { 52 | "styleExt": "css", 53 | "component": {} 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/app/shared/services/api.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { environment } from '../../../environments/environment'; 3 | import { HttpHeaders, HttpClient, HttpParams } from '@angular/common/http'; 4 | import { Observable } from 'rxjs/Observable'; 5 | 6 | import { JwtService } from './jwt.service'; 7 | import { ErrorObservable } from 'rxjs/observable/ErrorObservable'; 8 | import { catchError } from 'rxjs/operators/catchError'; 9 | 10 | @Injectable() 11 | export class ApiService { 12 | constructor( 13 | private http: HttpClient, 14 | private jwtService: JwtService 15 | ) {} 16 | 17 | private formatErrors(error: any) { 18 | return new ErrorObservable(error.json()); 19 | } 20 | 21 | get(path: string, params: HttpParams = new HttpParams()): Observable { 22 | return this.http.get(`${environment.api_url}${path}`, { params }) 23 | .pipe(catchError(this.formatErrors)); 24 | } 25 | 26 | put(path: string, body: Object = {}): Observable { 27 | return this.http.put( 28 | `${environment.api_url}${path}`, 29 | JSON.stringify(body) 30 | ).pipe(catchError(this.formatErrors)); 31 | } 32 | 33 | post(path: string, body: Object = {}): Observable { 34 | return this.http.post( 35 | `${environment.api_url}${path}`, 36 | JSON.stringify(body) 37 | ).pipe(catchError(this.formatErrors)); 38 | } 39 | 40 | delete(path): Observable { 41 | return this.http.delete( 42 | `${environment.api_url}${path}` 43 | ).pipe(catchError(this.formatErrors)); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ang2-conduit", 3 | "version": "0.0.0", 4 | "license": "MIT", 5 | "scripts": { 6 | "ng": "ng", 7 | "start": "ng serve", 8 | "build": "ng build --prod", 9 | "test": "ng test", 10 | "lint": "ng lint --force", 11 | "e2e": "ng e2e" 12 | }, 13 | "pre-commit": [ 14 | "lint" 15 | ], 16 | "private": true, 17 | "dependencies": { 18 | "@angular/animations": "^5.0.0", 19 | "@angular/common": "^5.0.0", 20 | "@angular/compiler": "^5.0.0", 21 | "@angular/core": "^5.0.0", 22 | "@angular/forms": "^5.0.0", 23 | "@angular/platform-browser": "^5.0.0", 24 | "@angular/platform-browser-dynamic": "^5.0.0", 25 | "@angular/router": "^5.0.0", 26 | "core-js": "^2.4.1", 27 | "marked": "^0.3.9", 28 | "rxjs": "^5.5.2", 29 | "zone.js": "^0.8.14" 30 | }, 31 | "devDependencies": { 32 | "@angular/cli": "^1.6.3", 33 | "@angular/compiler-cli": "^5.0.0", 34 | "@angular/language-service": "^5.0.0", 35 | "@types/jasmine": "~2.5.53", 36 | "@types/jasminewd2": "~2.0.2", 37 | "@types/node": "~6.0.60", 38 | "codelyzer": "^4.0.1", 39 | "jasmine-core": "~2.6.2", 40 | "jasmine-spec-reporter": "~4.1.0", 41 | "karma": "~1.7.0", 42 | "karma-chrome-launcher": "~2.1.1", 43 | "karma-cli": "~1.0.1", 44 | "karma-coverage-istanbul-reporter": "^1.2.1", 45 | "karma-jasmine": "~1.1.0", 46 | "karma-jasmine-html-reporter": "^0.2.2", 47 | "pre-commit": "^1.2.2", 48 | "protractor": "~5.1.2", 49 | "ts-node": "~3.2.0", 50 | "tslint": "~5.7.0", 51 | "typescript": "~2.4.2" 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/app/home/home.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { Router } from '@angular/router'; 3 | 4 | import { ArticleListConfig, TagsService, UserService } from '../shared'; 5 | 6 | @Component({ 7 | selector: 'app-home-page', 8 | templateUrl: './home.component.html', 9 | styleUrls: ['./home.component.css'] 10 | }) 11 | export class HomeComponent implements OnInit { 12 | constructor( 13 | private router: Router, 14 | private tagsService: TagsService, 15 | private userService: UserService 16 | ) {} 17 | 18 | isAuthenticated: boolean; 19 | listConfig: ArticleListConfig = { 20 | type: 'all', 21 | filters: {} 22 | }; 23 | tags: Array = []; 24 | tagsLoaded = false; 25 | 26 | ngOnInit() { 27 | this.userService.isAuthenticated.subscribe( 28 | (authenticated) => { 29 | this.isAuthenticated = authenticated; 30 | 31 | // set the article list accordingly 32 | if (authenticated) { 33 | this.setListTo('feed'); 34 | } else { 35 | this.setListTo('all'); 36 | } 37 | } 38 | ); 39 | 40 | this.tagsService.getAll() 41 | .subscribe(tags => { 42 | this.tags = tags; 43 | this.tagsLoaded = true; 44 | }); 45 | } 46 | 47 | setListTo(type: string = '', filters: Object = {}) { 48 | // If feed is requested but user is not authenticated, redirect to login 49 | if (type === 'feed' && !this.isAuthenticated) { 50 | this.router.navigateByUrl('/login'); 51 | return; 52 | } 53 | 54 | // Otherwise, set the list object 55 | this.listConfig = {type: type, filters: filters}; 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/app/shared/article-helpers/article-list.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, Input } from '@angular/core'; 2 | 3 | import { Article, ArticleListConfig } from '../models'; 4 | import { ArticlesService } from '../services'; 5 | 6 | @Component({ 7 | selector: 'app-article-list', 8 | styleUrls: ['article-list.component.css'], 9 | templateUrl: './article-list.component.html' 10 | }) 11 | export class ArticleListComponent { 12 | constructor ( 13 | private articlesService: ArticlesService 14 | ) {} 15 | 16 | @Input() limit: number; 17 | @Input() 18 | set config(config: ArticleListConfig) { 19 | if (config) { 20 | this.query = config; 21 | this.currentPage = 1; 22 | this.runQuery(); 23 | } 24 | } 25 | 26 | query: ArticleListConfig; 27 | results: Article[]; 28 | loading = false; 29 | currentPage = 1; 30 | totalPages: Array = [1]; 31 | 32 | setPageTo(pageNumber) { 33 | this.currentPage = pageNumber; 34 | this.runQuery(); 35 | } 36 | 37 | runQuery() { 38 | this.loading = true; 39 | this.results = []; 40 | 41 | // Create limit and offset filter (if necessary) 42 | if (this.limit) { 43 | this.query.filters.limit = this.limit; 44 | this.query.filters.offset = (this.limit * (this.currentPage - 1)); 45 | } 46 | 47 | this.articlesService.query(this.query) 48 | .subscribe(data => { 49 | this.loading = false; 50 | this.results = data.articles; 51 | 52 | // Used from http://www.jstips.co/en/create-range-0...n-easily-using-one-line/ 53 | this.totalPages = Array.from(new Array(Math.ceil(data.articlesCount / this.limit)), (val, index) => index + 1); 54 | }); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/app/app.module.ts: -------------------------------------------------------------------------------- 1 | import { ModuleWithProviders, NgModule } from '@angular/core'; 2 | import { BrowserModule } from '@angular/platform-browser'; 3 | import { RouterModule } from '@angular/router'; 4 | import { HTTP_INTERCEPTORS } from '@angular/common/http'; 5 | 6 | import { AppComponent } from './app.component'; 7 | import { ArticleModule } from './article/article.module'; 8 | import { AuthModule } from './auth/auth.module'; 9 | import { EditorModule } from './editor/editor.module'; 10 | import { HomeModule } from './home/home.module'; 11 | import { ProfileModule } from './profile/profile.module'; 12 | import { SettingsModule } from './settings/settings.module'; 13 | import { 14 | ApiService, 15 | ArticlesService, 16 | AuthGuard, 17 | CommentsService, 18 | FooterComponent, 19 | HeaderComponent, 20 | JwtService, 21 | ProfilesService, 22 | SharedModule, 23 | TagsService, 24 | UserService, 25 | HttpTokenInterceptor 26 | } from './shared'; 27 | 28 | const rootRouting: ModuleWithProviders = RouterModule.forRoot([]); 29 | 30 | @NgModule({ 31 | declarations: [ 32 | AppComponent, 33 | FooterComponent, 34 | HeaderComponent 35 | ], 36 | imports: [ 37 | BrowserModule, 38 | ArticleModule, 39 | AuthModule, 40 | EditorModule, 41 | HomeModule, 42 | ProfileModule, 43 | rootRouting, 44 | SharedModule, 45 | SettingsModule 46 | ], 47 | providers: [ 48 | { provide: HTTP_INTERCEPTORS, useClass: HttpTokenInterceptor, multi: true}, 49 | ApiService, 50 | ArticlesService, 51 | AuthGuard, 52 | CommentsService, 53 | JwtService, 54 | ProfilesService, 55 | TagsService, 56 | UserService 57 | ], 58 | bootstrap: [AppComponent] 59 | }) 60 | export class AppModule { } 61 | -------------------------------------------------------------------------------- /src/app/auth/auth.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 |
4 | 5 |
6 |

{{ title }}

7 |

8 | Have an account? 9 | Need an account? 10 |

11 | 12 |
13 |
14 |
15 | 21 |
22 |
23 | 28 |
29 |
30 | 35 |
36 | 39 |
40 |
41 |
42 | 43 |
44 |
45 |
46 | -------------------------------------------------------------------------------- /src/app/profile/profile.component.html: -------------------------------------------------------------------------------- 1 |
2 | 3 | 26 | 27 |
28 |
29 | 30 |
31 |
32 | 50 |
51 | 52 | 53 |
54 | 55 |
56 |
57 | 58 |
59 | -------------------------------------------------------------------------------- /src/app/shared/buttons/follow-button.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, EventEmitter, Input, Output } from '@angular/core'; 2 | import { Router } from '@angular/router'; 3 | 4 | import { Profile } from '../models'; 5 | import { ProfilesService, UserService } from '../services'; 6 | 7 | @Component({ 8 | selector: 'app-follow-button', 9 | templateUrl: './follow-button.component.html' 10 | }) 11 | export class FollowButtonComponent { 12 | constructor( 13 | private profilesService: ProfilesService, 14 | private router: Router, 15 | private userService: UserService 16 | ) {} 17 | 18 | @Input() profile: Profile; 19 | @Output() toggle = new EventEmitter(); 20 | isSubmitting = false; 21 | 22 | toggleFollowing() { 23 | this.isSubmitting = true; 24 | //TODO: remove nested subscribes, use mergeMap 25 | 26 | this.userService.isAuthenticated.subscribe( 27 | (authenticated) => { 28 | // Not authenticated? Push to login screen 29 | if (!authenticated) { 30 | this.router.navigateByUrl('/login'); 31 | return; 32 | } 33 | 34 | // Follow this profile if we aren't already 35 | if (!this.profile.following) { 36 | this.profilesService.follow(this.profile.username) 37 | .subscribe( 38 | data => { 39 | this.isSubmitting = false; 40 | this.toggle.emit(true); 41 | }, 42 | err => this.isSubmitting = false 43 | ); 44 | 45 | // Otherwise, unfollow this profile 46 | } else { 47 | this.profilesService.unfollow(this.profile.username) 48 | .subscribe( 49 | data => { 50 | this.isSubmitting = false; 51 | this.toggle.emit(false); 52 | }, 53 | err => this.isSubmitting = false 54 | ); 55 | } 56 | 57 | } 58 | ); 59 | 60 | 61 | } 62 | 63 | } 64 | -------------------------------------------------------------------------------- /src/app/shared/buttons/favorite-button.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, EventEmitter, Input, Output } from '@angular/core'; 2 | import { Router } from '@angular/router'; 3 | 4 | import { Article } from '../models'; 5 | import { ArticlesService, UserService } from '../services'; 6 | 7 | @Component({ 8 | selector: 'app-favorite-button', 9 | templateUrl: './favorite-button.component.html' 10 | }) 11 | export class FavoriteButtonComponent { 12 | constructor( 13 | private articlesService: ArticlesService, 14 | private router: Router, 15 | private userService: UserService 16 | ) {} 17 | 18 | @Input() article: Article; 19 | @Output() toggle = new EventEmitter(); 20 | isSubmitting = false; 21 | 22 | toggleFavorite() { 23 | this.isSubmitting = true; 24 | //TODO: remove nested subscribes, use mergeMap 25 | this.userService.isAuthenticated.subscribe( 26 | (authenticated) => { 27 | // Not authenticated? Push to login screen 28 | if (!authenticated) { 29 | this.router.navigateByUrl('/login'); 30 | return; 31 | } 32 | 33 | // Favorite the article if it isn't favorited yet 34 | if (!this.article.favorited) { 35 | this.articlesService.favorite(this.article.slug) 36 | .subscribe( 37 | data => { 38 | this.isSubmitting = false; 39 | this.toggle.emit(true); 40 | }, 41 | err => this.isSubmitting = false 42 | ); 43 | 44 | // Otherwise, unfavorite the article 45 | } else { 46 | this.articlesService.unfavorite(this.article.slug) 47 | .subscribe( 48 | data => { 49 | this.isSubmitting = false; 50 | this.toggle.emit(false); 51 | }, 52 | err => this.isSubmitting = false 53 | ); 54 | } 55 | 56 | } 57 | ); 58 | 59 | 60 | } 61 | 62 | } 63 | -------------------------------------------------------------------------------- /src/app/auth/auth.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { FormBuilder, FormGroup, FormControl, Validators } from '@angular/forms'; 3 | import { ActivatedRoute, Router } from '@angular/router'; 4 | 5 | import { Errors, UserService } from '../shared'; 6 | 7 | @Component({ 8 | selector: 'app-auth-page', 9 | templateUrl: './auth.component.html' 10 | }) 11 | export class AuthComponent implements OnInit { 12 | authType: String = ''; 13 | title: String = ''; 14 | errors: Errors = {errors: {}}; 15 | isSubmitting = false; 16 | authForm: FormGroup; 17 | 18 | constructor( 19 | private route: ActivatedRoute, 20 | private router: Router, 21 | private userService: UserService, 22 | private fb: FormBuilder 23 | ) { 24 | // use FormBuilder to create a form group 25 | this.authForm = this.fb.group({ 26 | 'email': ['', Validators.required], 27 | 'password': ['', Validators.required] 28 | }); 29 | } 30 | 31 | ngOnInit() { 32 | this.route.url.subscribe(data => { 33 | // Get the last piece of the URL (it's either 'login' or 'register') 34 | this.authType = data[data.length - 1].path; 35 | // Set a title for the page accordingly 36 | this.title = (this.authType === 'login') ? 'Sign in' : 'Sign up'; 37 | // add form control for username if this is the register page 38 | if (this.authType === 'register') { 39 | this.authForm.addControl('username', new FormControl()); 40 | } 41 | }); 42 | } 43 | 44 | submitForm() { 45 | this.isSubmitting = true; 46 | this.errors = {errors: {}}; 47 | 48 | const credentials = this.authForm.value; 49 | this.userService 50 | .attemptAuth(this.authType, credentials) 51 | .subscribe( 52 | data => this.router.navigateByUrl('/'), 53 | err => { 54 | this.errors = err; 55 | this.isSubmitting = false; 56 | } 57 | ); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/app/settings/settings.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { FormBuilder, FormGroup } from '@angular/forms'; 3 | import { Router } from '@angular/router'; 4 | 5 | import { User, UserService } from '../shared'; 6 | 7 | @Component({ 8 | selector: 'app-settings-page', 9 | templateUrl: './settings.component.html' 10 | }) 11 | export class SettingsComponent implements OnInit { 12 | user: User = {} as User; 13 | settingsForm: FormGroup; 14 | errors: Object = {}; 15 | isSubmitting = false; 16 | 17 | constructor( 18 | private router: Router, 19 | private userService: UserService, 20 | private fb: FormBuilder 21 | ) { 22 | // create form group using the form builder 23 | this.settingsForm = this.fb.group({ 24 | image: '', 25 | username: '', 26 | bio: '', 27 | email: '', 28 | password: '' 29 | }); 30 | // Optional: subscribe to changes on the form 31 | // this.settingsForm.valueChanges.subscribe(values => this.updateUser(values)); 32 | } 33 | 34 | ngOnInit() { 35 | // Make a fresh copy of the current user's object to place in editable form fields 36 | Object.assign(this.user, this.userService.getCurrentUser()); 37 | // Fill the form 38 | this.settingsForm.patchValue(this.user); 39 | } 40 | 41 | logout() { 42 | this.userService.purgeAuth(); 43 | this.router.navigateByUrl('/'); 44 | } 45 | 46 | submitForm() { 47 | this.isSubmitting = true; 48 | 49 | // update the model 50 | this.updateUser(this.settingsForm.value); 51 | 52 | this.userService 53 | .update(this.user) 54 | .subscribe( 55 | updatedUser => this.router.navigateByUrl('/profile/' + updatedUser.username), 56 | err => { 57 | this.errors = err; 58 | this.isSubmitting = false; 59 | } 60 | ); 61 | } 62 | 63 | updateUser(values: Object) { 64 | Object.assign(this.user, values); 65 | } 66 | 67 | } 68 | -------------------------------------------------------------------------------- /src/app/shared/services/articles.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { HttpParams } from '@angular/common/http'; 3 | import { Observable } from 'rxjs/Observable'; 4 | 5 | import { ApiService } from './api.service'; 6 | import { Article, ArticleListConfig } from '../models'; 7 | import { map } from 'rxjs/operators'; 8 | 9 | @Injectable() 10 | export class ArticlesService { 11 | constructor ( 12 | private apiService: ApiService 13 | ) {} 14 | 15 | query(config: ArticleListConfig): Observable<{articles: Article[], articlesCount: number}> { 16 | // Convert any filters over to Angular's URLSearchParams 17 | const params = {}; 18 | 19 | Object.keys(config.filters) 20 | .forEach((key) => { 21 | params[key] = config.filters[key]; 22 | }); 23 | 24 | return this.apiService 25 | .get( 26 | '/articles' + ((config.type === 'feed') ? '/feed' : ''), 27 | new HttpParams(params) 28 | ); 29 | } 30 | 31 | get(slug): Observable
{ 32 | return this.apiService.get('/articles/' + slug) 33 | .pipe(map(data => data.article)); 34 | } 35 | 36 | destroy(slug) { 37 | return this.apiService.delete('/articles/' + slug); 38 | } 39 | 40 | save(article): Observable
{ 41 | // If we're updating an existing article 42 | if (article.slug) { 43 | return this.apiService.put('/articles/' + article.slug, {article: article}) 44 | .pipe(map(data => data.article)); 45 | 46 | // Otherwise, create a new article 47 | } else { 48 | return this.apiService.post('/articles/', {article: article}) 49 | .pipe(map(data => data.article)); 50 | } 51 | } 52 | 53 | favorite(slug): Observable
{ 54 | return this.apiService.post('/articles/' + slug + '/favorite'); 55 | } 56 | 57 | unfavorite(slug): Observable
{ 58 | return this.apiService.delete('/articles/' + slug + '/favorite'); 59 | } 60 | 61 | 62 | } 63 | -------------------------------------------------------------------------------- /src/app/editor/editor.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 |
4 |
5 | 6 | 7 | 8 |
9 |
10 | 11 |
12 | 16 |
17 | 18 |
19 | 23 |
24 | 25 |
26 | 31 |
32 | 33 |
34 | 39 | 40 |
41 | 43 | 44 | {{ tag }} 45 | 46 |
47 |
48 | 49 | 52 | 53 |
54 |
55 | 56 |
57 |
58 |
59 |
60 | -------------------------------------------------------------------------------- /src/app/home/home.component.html: -------------------------------------------------------------------------------- 1 |
2 | 3 | 9 | 10 |
11 |
12 | 13 |
14 |
15 | 36 |
37 | 38 | 39 |
40 | 41 |
42 | 61 |
62 | 63 |
64 |
65 |
66 | -------------------------------------------------------------------------------- /src/app/shared/layout/header.component.html: -------------------------------------------------------------------------------- 1 | 76 | -------------------------------------------------------------------------------- /src/app/settings/settings.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 |
4 |
5 | 6 |

Your Settings

7 | 8 | 9 | 10 |
11 |
12 | 13 |
14 | 18 |
19 | 20 |
21 | 25 |
26 | 27 |
28 | 33 |
34 | 35 |
36 | 40 |
41 | 42 |
43 | 47 |
48 | 49 | 53 | 54 |
55 |
56 | 57 | 58 |
59 | 60 | 64 | 65 |
66 |
67 |
68 |
69 | -------------------------------------------------------------------------------- /src/app/editor/editor.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { FormBuilder, FormGroup, FormControl } from '@angular/forms'; 3 | import { ActivatedRoute, Router } from '@angular/router'; 4 | 5 | import { Article, ArticlesService } from '../shared'; 6 | 7 | @Component({ 8 | selector: 'app-editor-page', 9 | templateUrl: './editor.component.html' 10 | }) 11 | export class EditorComponent implements OnInit { 12 | article: Article = {} as Article; 13 | articleForm: FormGroup; 14 | tagField = new FormControl(); 15 | errors: Object = {}; 16 | isSubmitting = false; 17 | 18 | constructor( 19 | private articlesService: ArticlesService, 20 | private route: ActivatedRoute, 21 | private router: Router, 22 | private fb: FormBuilder 23 | ) { 24 | // use the FormBuilder to create a form group 25 | this.articleForm = this.fb.group({ 26 | title: '', 27 | description: '', 28 | body: '', 29 | }); 30 | // Optional: subscribe to value changes on the form 31 | // this.articleForm.valueChanges.subscribe(value => this.updateArticle(value)); 32 | } 33 | 34 | ngOnInit() { 35 | // If there's an article prefetched, load it 36 | this.route.data.subscribe( 37 | (data: {article: Article}) => { 38 | if (data.article) { 39 | this.article = data.article; 40 | this.articleForm.patchValue(data.article); 41 | } 42 | } 43 | ); 44 | } 45 | 46 | addTag() { 47 | // retrieve tag control 48 | const tag = this.tagField.value; 49 | // only add tag if it does not exist yet 50 | if (this.article.tagList.indexOf(tag) < 0) { 51 | this.article.tagList.push(tag); 52 | } 53 | // clear the input 54 | this.tagField.reset(''); 55 | } 56 | 57 | removeTag(tagName: string) { 58 | this.article.tagList = this.article.tagList.filter((tag) => tag !== tagName); 59 | } 60 | 61 | submitForm() { 62 | this.isSubmitting = true; 63 | 64 | // update the model 65 | this.updateArticle(this.articleForm.value); 66 | 67 | // post the changes 68 | this.articlesService 69 | .save(this.article) 70 | .subscribe( 71 | article => this.router.navigateByUrl('/article/' + article.slug), 72 | err => { 73 | this.errors = err; 74 | this.isSubmitting = false; 75 | } 76 | ); 77 | } 78 | 79 | updateArticle(values: Object) { 80 | Object.assign(this.article, values); 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/polyfills.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file includes polyfills needed by Angular and is loaded before the app. 3 | * You can add your own extra polyfills to this file. 4 | * 5 | * This file is divided into 2 sections: 6 | * 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers. 7 | * 2. Application imports. Files imported after ZoneJS that should be loaded before your main 8 | * file. 9 | * 10 | * The current setup is for so-called "evergreen" browsers; the last versions of browsers that 11 | * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera), 12 | * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile. 13 | * 14 | * Learn more in https://angular.io/docs/ts/latest/guide/browser-support.html 15 | */ 16 | 17 | /*************************************************************************************************** 18 | * BROWSER POLYFILLS 19 | */ 20 | 21 | /** IE9, IE10 and IE11 requires all of the following polyfills. **/ 22 | import 'core-js/es6/symbol'; 23 | import 'core-js/es6/object'; 24 | import 'core-js/es6/function'; 25 | import 'core-js/es6/parse-int'; 26 | import 'core-js/es6/parse-float'; 27 | import 'core-js/es6/number'; 28 | import 'core-js/es6/math'; 29 | import 'core-js/es6/string'; 30 | import 'core-js/es6/date'; 31 | import 'core-js/es6/array'; 32 | import 'core-js/es6/regexp'; 33 | import 'core-js/es6/map'; 34 | // import 'core-js/es6/weak-map'; 35 | import 'core-js/es6/set'; 36 | 37 | /** IE10 and IE11 requires the following for NgClass support on SVG elements */ 38 | // import 'classlist.js'; // Run `npm install --save classlist.js`. 39 | 40 | /** IE10 and IE11 requires the following for the Reflect API. */ 41 | // import 'core-js/es6/reflect'; 42 | 43 | /** Evergreen browsers require these. **/ 44 | // Used for reflect-metadata in JIT. If you use AOT (and only Angular decorators), you can remove. 45 | import 'core-js/es7/reflect'; 46 | 47 | /** 48 | * Required to support Web Animations `@angular/platform-browser/animations`. 49 | * Needed for: All but Chrome, Firefox and Opera. http://caniuse.com/#feat=web-animation 50 | **/ 51 | // import 'web-animations-js'; // Run `npm install --save web-animations-js`. 52 | 53 | /*************************************************************************************************** 54 | * Zone JS is required by default for Angular itself. 55 | */ 56 | import 'zone.js/dist/zone'; // Included with Angular CLI. 57 | 58 | /*************************************************************************************************** 59 | * APPLICATION IMPORTS 60 | */ 61 | -------------------------------------------------------------------------------- /src/app/shared/services/user.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { HttpClient } from '@angular/common/http'; 3 | import { Observable } from 'rxjs/Observable'; 4 | import { BehaviorSubject } from 'rxjs/BehaviorSubject'; 5 | import { ReplaySubject } from 'rxjs/ReplaySubject'; 6 | 7 | import { ApiService } from './api.service'; 8 | import { JwtService } from './jwt.service'; 9 | import { User } from '../models'; 10 | import { distinctUntilChanged, map } from 'rxjs/operators'; 11 | 12 | 13 | @Injectable() 14 | export class UserService { 15 | private currentUserSubject = new BehaviorSubject({} as User); 16 | public currentUser = this.currentUserSubject.asObservable().pipe(distinctUntilChanged()); 17 | 18 | private isAuthenticatedSubject = new ReplaySubject(1); 19 | public isAuthenticated = this.isAuthenticatedSubject.asObservable(); 20 | 21 | constructor ( 22 | private apiService: ApiService, 23 | private http: HttpClient, 24 | private jwtService: JwtService 25 | ) {} 26 | 27 | // Verify JWT in localstorage with server & load user's info. 28 | // This runs once on application startup. 29 | populate() { 30 | // If JWT detected, attempt to get & store user's info 31 | if (this.jwtService.getToken()) { 32 | this.apiService.get('/user') 33 | .subscribe( 34 | data => this.setAuth(data.user), 35 | err => this.purgeAuth() 36 | ); 37 | } else { 38 | // Remove any potential remnants of previous auth states 39 | this.purgeAuth(); 40 | } 41 | } 42 | 43 | setAuth(user: User) { 44 | // Save JWT sent from server in localstorage 45 | this.jwtService.saveToken(user.token); 46 | // Set current user data into observable 47 | this.currentUserSubject.next(user); 48 | // Set isAuthenticated to true 49 | this.isAuthenticatedSubject.next(true); 50 | } 51 | 52 | purgeAuth() { 53 | // Remove JWT from localstorage 54 | this.jwtService.destroyToken(); 55 | // Set current user to an empty object 56 | this.currentUserSubject.next({} as User); 57 | // Set auth status to false 58 | this.isAuthenticatedSubject.next(false); 59 | } 60 | 61 | attemptAuth(type, credentials): Observable { 62 | const route = (type === 'login') ? '/login' : ''; 63 | return this.apiService.post('/users' + route, {user: credentials}) 64 | .pipe(map( 65 | data => { 66 | this.setAuth(data.user); 67 | return data; 68 | } 69 | )); 70 | } 71 | 72 | getCurrentUser(): User { 73 | return this.currentUserSubject.value; 74 | } 75 | 76 | // Update the user on the server (email, pass, etc) 77 | update(user): Observable { 78 | return this.apiService 79 | .put('/user', { user }) 80 | .pipe(map(data => { 81 | // Update the currentUser observable 82 | this.currentUserSubject.next(data.user); 83 | return data.user; 84 | })); 85 | } 86 | 87 | } 88 | -------------------------------------------------------------------------------- /src/app/article/article.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { FormControl } from '@angular/forms'; 3 | import { ActivatedRoute, Router } from '@angular/router'; 4 | 5 | import { 6 | Article, 7 | ArticlesService, 8 | Comment, 9 | CommentsService, 10 | User, 11 | UserService 12 | } from '../shared'; 13 | 14 | @Component({ 15 | selector: 'app-article-page', 16 | templateUrl: './article.component.html' 17 | }) 18 | export class ArticleComponent implements OnInit { 19 | article: Article; 20 | currentUser: User; 21 | canModify: boolean; 22 | comments: Comment[]; 23 | commentControl = new FormControl(); 24 | commentFormErrors = {}; 25 | isSubmitting = false; 26 | isDeleting = false; 27 | 28 | constructor( 29 | private route: ActivatedRoute, 30 | private articlesService: ArticlesService, 31 | private commentsService: CommentsService, 32 | private router: Router, 33 | private userService: UserService, 34 | ) { } 35 | 36 | ngOnInit() { 37 | // Retreive the prefetched article 38 | this.route.data.subscribe( 39 | (data: { article: Article }) => { 40 | this.article = data.article; 41 | 42 | // Load the comments on this article 43 | this.populateComments(); 44 | } 45 | ); 46 | 47 | // Load the current user's data 48 | this.userService.currentUser.subscribe( 49 | (userData: User) => { 50 | this.currentUser = userData; 51 | 52 | this.canModify = (this.currentUser.username === this.article.author.username); 53 | } 54 | ); 55 | } 56 | 57 | onToggleFavorite(favorited: boolean) { 58 | this.article.favorited = favorited; 59 | 60 | if (favorited) { 61 | this.article.favoritesCount++; 62 | } else { 63 | this.article.favoritesCount--; 64 | } 65 | } 66 | 67 | onToggleFollowing(following: boolean) { 68 | this.article.author.following = following; 69 | } 70 | 71 | deleteArticle() { 72 | this.isDeleting = true; 73 | 74 | this.articlesService.destroy(this.article.slug) 75 | .subscribe( 76 | success => { 77 | this.router.navigateByUrl('/'); 78 | } 79 | ); 80 | } 81 | 82 | populateComments() { 83 | this.commentsService.getAll(this.article.slug) 84 | .subscribe(comments => this.comments = comments); 85 | } 86 | 87 | addComment() { 88 | this.isSubmitting = true; 89 | this.commentFormErrors = {}; 90 | 91 | const commentBody = this.commentControl.value; 92 | this.commentsService 93 | .add(this.article.slug, commentBody) 94 | .subscribe( 95 | comment => { 96 | this.comments.unshift(comment); 97 | this.commentControl.reset(''); 98 | this.isSubmitting = false; 99 | }, 100 | errors => { 101 | this.isSubmitting = false; 102 | this.commentFormErrors = errors; 103 | } 104 | ); 105 | } 106 | 107 | onDeleteComment(comment) { 108 | this.commentsService.destroy(comment.id, this.article.slug) 109 | .subscribe( 110 | success => { 111 | this.comments = this.comments.filter((item) => item !== comment); 112 | } 113 | ); 114 | } 115 | 116 | } 117 | -------------------------------------------------------------------------------- /tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "rulesDirectory": [ 3 | "node_modules/codelyzer" 4 | ], 5 | "rules": { 6 | "arrow-return-shorthand": true, 7 | "callable-types": true, 8 | "class-name": true, 9 | "comment-format": [ 10 | true, 11 | "check-space" 12 | ], 13 | "curly": true, 14 | "deprecation": { 15 | "severity": "warn" 16 | }, 17 | "eofline": true, 18 | "forin": true, 19 | "import-blacklist": [ 20 | true, 21 | "rxjs", 22 | "rxjs/Rx" 23 | ], 24 | "import-spacing": true, 25 | "indent": [ 26 | true, 27 | "spaces" 28 | ], 29 | "interface-over-type-literal": true, 30 | "label-position": true, 31 | "max-line-length": [ 32 | true, 33 | 140 34 | ], 35 | "member-access": false, 36 | "member-ordering": [ 37 | true, 38 | { 39 | "order": [ 40 | "static-field", 41 | "instance-field", 42 | "static-method", 43 | "instance-method" 44 | ] 45 | } 46 | ], 47 | "no-arg": true, 48 | "no-bitwise": true, 49 | "no-console": [ 50 | true, 51 | "debug", 52 | "info", 53 | "time", 54 | "timeEnd", 55 | "trace" 56 | ], 57 | "no-construct": true, 58 | "no-debugger": true, 59 | "no-duplicate-super": true, 60 | "no-empty": false, 61 | "no-empty-interface": true, 62 | "no-eval": true, 63 | "no-inferrable-types": [ 64 | true, 65 | "ignore-params" 66 | ], 67 | "no-misused-new": true, 68 | "no-non-null-assertion": true, 69 | "no-shadowed-variable": true, 70 | "no-string-literal": false, 71 | "no-string-throw": true, 72 | "no-switch-case-fall-through": true, 73 | "no-trailing-whitespace": true, 74 | "no-unnecessary-initializer": true, 75 | "no-unused-expression": true, 76 | "no-use-before-declare": true, 77 | "no-var-keyword": true, 78 | "object-literal-sort-keys": false, 79 | "one-line": [ 80 | true, 81 | "check-open-brace", 82 | "check-catch", 83 | "check-else", 84 | "check-whitespace" 85 | ], 86 | "prefer-const": true, 87 | "quotemark": [ 88 | true, 89 | "single" 90 | ], 91 | "radix": true, 92 | "semicolon": [ 93 | true, 94 | "always" 95 | ], 96 | "triple-equals": [ 97 | true, 98 | "allow-null-check" 99 | ], 100 | "typedef-whitespace": [ 101 | true, 102 | { 103 | "call-signature": "nospace", 104 | "index-signature": "nospace", 105 | "parameter": "nospace", 106 | "property-declaration": "nospace", 107 | "variable-declaration": "nospace" 108 | } 109 | ], 110 | "typeof-compare": true, 111 | "unified-signatures": true, 112 | "variable-name": false, 113 | "whitespace": [ 114 | true, 115 | "check-branch", 116 | "check-decl", 117 | "check-operator", 118 | "check-separator", 119 | "check-type" 120 | ], 121 | "directive-selector": [ 122 | true, 123 | "attribute", 124 | "app", 125 | "camelCase" 126 | ], 127 | "component-selector": [ 128 | true, 129 | "element", 130 | "app", 131 | "kebab-case" 132 | ], 133 | "no-output-on-prefix": true, 134 | "use-input-property-decorator": true, 135 | "use-output-property-decorator": true, 136 | "use-host-property-decorator": true, 137 | "no-input-rename": true, 138 | "no-output-rename": true, 139 | "use-life-cycle-interface": true, 140 | "use-pipe-transform-interface": true, 141 | "component-class-suffix": true, 142 | "directive-class-suffix": true 143 | } 144 | } 145 | -------------------------------------------------------------------------------- /src/app/article/article.component.html: -------------------------------------------------------------------------------- 1 |
2 | 3 | 38 | 39 |
40 | 41 |
42 |
43 | 44 |
45 | 46 |
    47 |
  • 49 | {{ tag }} 50 |
  • 51 |
52 | 53 |
54 |
55 | 56 |
57 | 58 |
59 | 60 | 61 | 62 | 64 | Edit Article 65 | 66 | 67 | 72 | 73 | 74 | 75 | 78 | 79 | 80 | 83 | {{ article.favorited ? 'Unfavorite' : 'Favorite' }} Article ({{ article.favoritesCount }}) 84 | 85 | 86 | 87 | 88 |
89 | 90 |
91 |
92 | 93 |
94 | 95 |
96 |
97 |
98 | 103 |
104 | 110 |
111 |
112 |
113 | 114 |
115 | Sign in or sign up to add comments on this article. 116 |
117 | 118 | 122 | 123 | 124 |
125 |
126 | 127 |
128 |
129 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ![Angular 2 Example App](logo.png) 2 | 3 | > ### Angular 5 codebase containing real world examples (CRUD, auth, advanced patterns, etc) that adheres to the [RealWorld](https://github.com/gothinkster/realworld-example-apps) spec and API. 4 | 5 | 6 |    7 | 8 | ### [Demo](https://angular2.realworld.io)    [RealWorld](https://github.com/gothinkster/realworld) 9 | 10 | 11 | 12 | This codebase was created to demonstrate a fully fledged application built with Angular that interacts with an actual backend server including CRUD operations, authentication, routing, pagination, and more. We've gone to great lengths to adhere to the [Angular Styleguide](https://angular.io/styleguide) & best practices. 13 | 14 | Additionally, there is an Angular 1.5 version of this codebase that you can [fork](https://github.com/gothinkster/angularjs-realworld-example-app) and/or [learn how to recreate](https://thinkster.io/angularjs-es6-tutorial). 15 | 16 | 17 | # How it works 18 | 19 | We're currently working on some docs for the codebase (explaining where functionality is located, how it works, etc) but the codebase should be straightforward to follow as is. We've also released a [step-by-step tutorial w/ screencasts](https://thinkster.io/tutorials/building-real-world-angular-2-apps) that teaches you how to recreate the codebase from scratch. 20 | 21 | ### Making requests to the backend API 22 | 23 | For convenience, we have a live API server running at https://conduit.productionready.io/api for the application to make requests against. You can view [the API spec here](https://github.com/GoThinkster/productionready/blob/master/api) which contains all routes & responses for the server. 24 | 25 | The source code for the backend server (available for Node, Rails and Django) can be found in the [main RealWorld repo](https://github.com/gothinkster/realworld). 26 | 27 | If you want to change the API URL to a local server, simply edit `src/environments/environment.ts` and change `api_url` to the local server's URL (i.e. `localhost:3000/api`) 28 | 29 | 30 | # Getting started 31 | 32 | Make sure you have the [Angular CLI](https://github.com/angular/angular-cli#installation) installed globally, then run `npm install` to resolve all dependencies (might take a minute). 33 | 34 | Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files. 35 | 36 | ### Building the project 37 | Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. Use the `-prod` flag for a production build. 38 | 39 | 40 | ## Functionality overview 41 | 42 | The example application is a social blogging site (i.e. a Medium.com clone) called "Conduit". It uses a custom API for all requests, including authentication. You can view a live demo over at https://angular2.realworld.io 43 | 44 | **General functionality:** 45 | 46 | - Authenticate users via JWT (login/signup pages + logout button on settings page) 47 | - CRU* users (sign up & settings page - no deleting required) 48 | - CRUD Articles 49 | - CR*D Comments on articles (no updating required) 50 | - GET and display paginated lists of articles 51 | - Favorite articles 52 | - Follow other users 53 | 54 | **The general page breakdown looks like this:** 55 | 56 | - Home page (URL: /#/ ) 57 | - List of tags 58 | - List of articles pulled from either Feed, Global, or by Tag 59 | - Pagination for list of articles 60 | - Sign in/Sign up pages (URL: /#/login, /#/register ) 61 | - Uses JWT (store the token in localStorage) 62 | - Authentication can be easily switched to session/cookie based 63 | - Settings page (URL: /#/settings ) 64 | - Editor page to create/edit articles (URL: /#/editor, /#/editor/article-slug-here ) 65 | - Article page (URL: /#/article/article-slug-here ) 66 | - Delete article button (only shown to article's author) 67 | - Render markdown from server client side 68 | - Comments section at bottom of page 69 | - Delete comment button (only shown to comment's author) 70 | - Profile page (URL: /#/profile/:username, /#/profile/:username/favorites ) 71 | - Show basic user info 72 | - List of articles populated from author's created articles or author's favorited articles 73 | 74 | 75 |
76 | 77 | [![Brought to you by Thinkster](https://raw.githubusercontent.com/gothinkster/realworld/master/media/end.png)](https://thinkster.io) 78 | --------------------------------------------------------------------------------