web-dave / angular-starter-v2

6 stars 3 forks source link

Create a Service #8

Open web-dave opened 7 years ago

web-dave commented 7 years ago
web-dave commented 7 years ago

install

  npm i --save-dev bookmonkey-api

generate

  ng g service books/shared/books -m=books/books.module
web-dave commented 7 years ago

package.json:

...
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "rest": "bookmonkey-api" // <---
  },
  ...

run this script

npm run rest

web-dave commented 7 years ago

API:

GET     /books          // Get all books
GET     /books/:isbn    // Get a specific book by ISBN
POST    /books          // Create a new book
PUT     /books/:isbn    // Update a book by ISBN
DELETE  /books/:isbn    // Delete a book by ISBN
web-dave commented 7 years ago

books.module.ts

import { HttpClientModule } from '@angular/common/http';
...

@NgModule({
  ... 
  imports: [
    ... ,
    HttpClientModule //  <---
  ],
  ...
})
export class BooksModule { }
web-dave commented 7 years ago

books.service.ts

import { HttpClient } from '@angular/common/http';

  restRoot = 'http://localhost:4730/books';

  constructor(private http: HttpClient) { }

  getBooks() {
    const url = this.restRoot;
    return this.http.get(url);
  }