GithubHelp home page GithubHelp logo

ng2-api's Introduction

ng2-api

Angular2 API services that wrap Http. See full client and server example ng2-api-examples

Install

npm i --save ng2-api

Usage

auth.guard.ts

import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';

export function authenticated(): boolean {
  return !!localStorage.getItem('token');
}

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private router: Router) {}

  canActivate() {
    if (authenticated()) { return true; }

    // Navigate to the login page
    this.router.navigate(['/login']);
    return false;
  }
}

auth.service.ts

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { ApiHttp } from 'ng2-api';
import { authenticated } from './auth.guard';

@Injectable()
export class AuthService {
  user: Object;
  authenticated: boolean = authenticated();

  constructor(protected http: ApiHttp,
              protected router: Router) {
    try {
      this.user = JSON.parse(localStorage.getItem('profile'));
    } catch(e) {
      this.user = {};
    }
  }

  login(params: any) {
    return this.http.post('login', JSON.stringify(params))
      .subscribe((res: Response) => {
        let {token, user} = res.json();
        let {token, user} = {token: 'abc', user: params};
        localStorage.setItem('profile', JSON.stringify(user));
        this.http.config.token = token;
        this.authenticated = true;
        this.user = user;
        this.router.navigate(['/admin/posts']);
      });
  }

  logout() {
    localStorage.removeItem('profile');
    this.http.config.token = '';
    this.authenticated = false;
    this.user = null;
    this.router.navigate(['/login']);
  }
}

app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpModule, Http } from '@angular/http';
import { FormsModule } from '@angular/forms';
import { ApiConfig, ApiHttp } from './ng2-api';

import { AppComponent } from './app.component';
import { AuthService } from './shared/auth.service';
import { PostsComponent } from './posts/posts.component';
import { PostsService } from './posts/posts.service';
import { routing } from './app.routing';

@NgModule({
  imports: [
    BrowserModule,
    HttpModule,
    FormsModule,
    routing
  ],
  declarations: [
    AppComponent,
    PostsComponent,
  ],
  providers: [
    {
      provide: ApiHttp,
      useFactory: (http: Http) => new ApiHttp(new ApiConfig({baseUrl: '/api'}), http),
      deps: [Http]
    },
    AuthService,
    PostsService,
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

posts.service.ts

import { Injectable } from '@angular/core';
import { ApiService } from 'ng2-api';

export interface Post {
  id?: number;
  title: string;
  body: string;
}

@Injectable()
export class PostsService extends ApiService<Post> {
  constructor(protected http: ApiHttp) {
    super(http, 'posts');
  }
}

ApiService methods

find(id: number | string): Observable<Post>
findAll(search?: any): Observable<Post[]>
create(model: Post): Observable<Post>
update(model: Post): Observable<Post>
delete(model: Post): Observable<boolean>

ApiService customization

You can customize resource path and provide optional config to super().

If need, you can also overwrite ApiService public (i.e. update) and private methods (i.e. serialize, deserialize)

Example:

@Injectable()
export class PostsService extends ApiService<Post> {
  constructor(protected http: ApiHttp) {
    super(http, 'posts', { 
      arrayRoot: 'posts',
      objectRoot: 'post'
    });
  }
}

Tests

npm i
npm test

License

MIT

ng2-api's People

Contributors

tb avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

ng2-api's Issues

typings not found

This runs after installing ng2-api. It seems like the post-install script is trying to run typings in a missing directory.

error TS6053: File 'typings/index.d.ts' not found.
npm ERR! Windows_NT 10.0.10586
npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "run" "build"
npm ERR! node v6.1.0
npm ERR! npm  v3.8.6
npm ERR! code ELIFECYCLE
npm ERR! [email protected] build: `typings install && tsc`
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the [email protected] build script 'typings install && tsc'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the ng2-api package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     typings install && tsc
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs ng2-api
npm ERR! Or if that isn't available, you can get their info via

License?

What license is this? Are you going to do any more with it?

Add example custom findAll that handles pagination

findAll(search?: any): Observable<T[]> will not work for pagination, where we need at least 2 results: array of T objets and total count (also page number or offset might be good).

Paginations can be quire custom, so there might be no point in trying to abstract it into service, instead
add example custom findAll that handles pagination.

NOTE: Consider to refactor deserialize so that it can be reused as in the paginated findAll.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.