Angular: invocando al backend

Ahora debemos modificar nuestro servicio para que no utilice data mock sino que invoque al backend express que habíamos definido anteriormente.

Para eso usaremos el modulo angular/http. Comenzaremos instalandolo mediante npm

$ npm install @angular/http --save

Luego en bootstrap.js importaremos dicho modulo y lo registraremos como dependencia del nuestro.

... import { HttpModule } from '@angular/http'; import 'rxjs/add/operator/toPromise' ...

src/frontend/bootstrap.js

@NgModule({ imports: [ BrowserModule, FormsModule, HttpModule ], styleUrls: ['./style.css'], declarations: [ PostComponent, NewPostComponent, AppComponent ], bootstrap: [ AppComponent ] }) class AppModule { }

Primera llamada HTTP

Ahora estamos listos para modificar el código de nuestro servicio para que, en lugar de crear la colección de posts de la siguiente forma:

src/frontend/app/sevices/post.service.js

constructor() { this._posts = [ { title: 'Noticia 1', content: 'Contenido 1', author: 'Claudio', upvotes: 1 }, { title: 'Noticia 2', content: 'Contenido 2', author: 'Claudio', upvotes: 3 }, { title: 'Noticia 3', content: 'Contenido 3', author: 'Claudio', upvotes: 0 } ] }

Para que reciba un servicio Http y haga una request al mismo para recuperar los datos.

src/frontend/app/sevices/post.service.js

constructor(http) { this.http = http this._posts = [] this.http.get("/noticias").toPromise() .then(response => this._posts.push(...response.json())) .catch(err => console.log(err)) }

Desde luego tuvimos que importar el servicio Http por medio de import { Http } from '@angular/http' y registrar el tipo del parametro http del constructor por medio de:

PostService.parameters = [
  Http
]

Ahora solo resta cambiar el método create para que delegue en el backend.

src/frontend/app/sevices/post.service.js

create(post) { this.http.post("/noticias", JSON.stringify(post), { headers:{'Content-Type': 'application/json'}}) .toPromise() .then(response => this._posts.push(post)) .catch(err => console.log(err)) }

Algunos datos utiles

  • JSON.stringify(post) - escribe un json a partir del objeto post envíado.
  • { headers:{'Content-Type': 'application/json'}} - instruye a angular http service de envíar el header Content-Type: application/json como parte de la request. Dicho header es necesario para que el modulo bodyParser de express interprete correctamente que el cuerpo se trata de un json y lo parsee correctamente.

results matching ""

    No results matching ""