npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

angular2-active-record

v0.1.5

Published

Helper library for handling connect api in Angular 2

Downloads

5

Readme

angular2-active-record

angular2-active-record is a helper library for connect api in your Angular 2 applications.

Installation

npm install angular2-active-record

Usage

config

The first config system app same as:

System.config({
  transpiler: 'typescript', 
  typescriptOptions: { emitDecoratorMetadata: true },
  baseURL: '/',
  packages: {        
    app: {
      format: 'register',
      defaultExtension: 'js'
    }
  },
  map: {
      "angular2-active-record": "node_modules/angular2-active-record/angular2-active-record.js"
  },
});

Config main app:

import {ApiConfig} from 'angular2-active-record';

...

class App {

}

bootstrap(App, [
  HTTP_PROVIDERS,
  provide(ApiConfig, {
    useValue: new ApiConfig({
      urlAPI: "http://localhost:3456/api/"
    })
  }),
  
])

A default configuration for urlAPI, header, methods details is provided:

  • urlAPI: http://localhost:3456/api/
  • headers: {'Content-Type': 'application/json'}
  • methods: {query: "get",update: "put", insert:"post",delete: "delete"}

If you wish to configure the urlPI, headers, methods, you can pass a config object when ApiConfig is injected.

...

bootstrap(App, [
  HTTP_PROVIDERS,
  provide(ApiConfig, {
    useValue: new ApiConfig({
      urlAPI: "http://localhost:3456/api/",
      headers: {},
      methods: {
        query: "get",
        update: "put",
        insert: "post",
        delete: "delete"
      }
    })
  }),
])

Write services to connect api

Example: a service to connect api for posts, and have apis as follow:

[GET]http://localhost:3456/api/posts # get all post
[GET]http://localhost:3456/api/posts/1 # show detail a post
[POST]http://localhost:3456/api/posts # create a post
[PUT]http://localhost:3456/api/posts/1 # update for post that post id = 1
[DELETE]http://localhost:3456/api/posts/1 # delete a post that post id = 1
import {Injectable}         from 'angular2/core';
import {Response}           from 'angular2/http';
import {Http, Headers, RequestOptions}from 'angular2/http';
import {Observable}         from 'rxjs/Observable';

import {ActiveRecord, ApiConfig} from 'angular2-active-record';

export interface Post {
  title: string;
  content: string;
  created_at?: Date;
  status?: boolean;
}


@Injectable()
export class PostService extends ActiveRecord<Post> {
  constructor(public options: ApiConfig, public http: Http) { 
    super(options, http, "posts");
  }
}

use PostService in post component:

import {Component, OnInit} from 'angular2/core';

import {MATERIAL_DIRECTIVES} from 'ng2-material/all';
import {AuthHttp, AuthConfig, tokenNotExpired, JwtHelper} from "angular2-jwt";
import {Router, RouteConfig, ROUTER_DIRECTIVES} from 'angular2/router';

import {Post} from '../models/post.model';
import {PostService} from '../services/post.service';

@Component({
  selector: 'posts',
  templateUrl: '/app/components/posts.component.html',
  directives: [MATERIAL_DIRECTIVES],
  providers: [PostService]
})

export class PostsComponent implements OnInit {
  constructor(private _postService: PostService, private _parentRouter: Router) {
  }
  errorMessage: string;
  posts: Post[];

  ngOnInit() { this.getPosts(); }

  getPosts() {
    this._postService.findAll()
      .subscribe(
        posts => this.posts = posts,
        error => this.errorMessage = error
      );
  }
  updatePost(id, post: Post) {
    this._postService.update(id, {post: post}).subscribe (
        res => {}
      );
  }
  createPost(post: Post) {
    this._postService.insert( {post: post}).subscribe (
        res => {}
      );
  }
  showPost(id) {
    this._postService.find(id).subscribe(
        res => {}
     );
  }
  deletePost(id) {
    this._postService.delete(id).subscribe(
        res => {}
      );
  }
}

If you want to use angular2-jwt to authenticate after login, post.service same as:

@Injectable()
export class PostService extends ActiveRecord<Post> {
  constructor(public options: ApiConfig, public http: AuthHttp) { 
    super(options, http, "posts");
  }
}

If you want to customize response data or handle error response, you must override processData and handleError in `post.service

  protected processData(res: Response) {
    return <T>res.json();
  }

  protected handleError(error: Response): ErrorObservable {
    return Observable.throw(new Error(error.json().join() || 'Server error'));
  }

Furthermore, you can override generateParam function to define query params of api:

protected generateParam(params: any = {}): string {
    let params_arr: Array<string> = [];
    for (let key in params) {
      if (params[key]) {
        params_arr.push(key + "=" + params[key]);
      }
    }
    return "?" + params_arr.join("&");
  }

License

This project is licensed under the MIT license. See the LICENSE file for more info.