Angular 2 http.post () no está enviando la solicitud
Cuando hago una solicitud post, angular 2 http no envía esta solicitud
this.http.post(this.adminUsersControllerRoute, JSON.stringify(user), this.getRequestOptions())
El http post no se envía al servidor, pero si hago la solicitud de esta manera
this.http.post(this.adminUsersControllerRoute, JSON.stringify(user), this.getRequestOptions()).subscribe(r=>{});
¿Es esta la intención y si lo es puede alguien explicarme por qué ? O es un bug ?
3 answers
Dado que el método post
de la clase Http
devuelve un observable, debe suscribirlo para ejecutar su procesamiento de inicialización. Los Observables son perezosos.
Deberías echar un vistazo a este video para más detalles:
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-24 19:43:01
El método Get no requiere usar el método subscribe, pero el método post requiere la suscripción. Los códigos de muestra Get y post están a continuación.
import { Component, OnInit } from '@angular/core'
import { Http, RequestOptions, Headers } from '@angular/http'
import 'rxjs/add/operator/map'
import 'rxjs/add/operator/catch'
import { Post } from './model/post'
import { Observable } from "rxjs/Observable";
@Component({
templateUrl: './test.html',
selector: 'test'
})
export class NgFor implements OnInit {
posts: Observable<Post[]>
model: Post = new Post()
/**
*
*/
constructor(private http: Http) {
}
ngOnInit(){
this.list()
}
private list(){
this.posts = this.http.get("http://localhost:3000/posts").map((val, i) => <Post[]>val.json())
}
public addNewRecord(){
let bodyString = JSON.stringify(this.model); // Stringify payload
let headers = new Headers({ 'Content-Type': 'application/json' }); // ... Set content type to JSON
let options = new RequestOptions({ headers: headers }); // Create a request option
this.http.post("http://localhost:3000/posts", this.model, options) // ...using post request
.map(res => res.json()) // ...and calling .json() on the response to return data
.catch((error:any) => Observable.throw(error.json().error || 'Server error')) //...errors if
.subscribe();
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-01 20:47:33
Debe suscribirse al observable devuelto si desea que se ejecute la llamada.
Vea también la documentación Http .
¡Suscríbete siempre!
Un método
HttpClient
no comienza su petición HTTP hasta que llame a subscribe() en el observable devuelto por ese método. Esto es cierto para todos los métodosHttpClient
.El AsyncPipe se suscribe (y cancela su suscripción) para usted automáticamente.
Todos los observables devueltos desde
HttpClient
los métodos son fríos por diseño. La ejecución de la solicitud HTTP es diferida, lo que le permite extender el observable con operaciones adicionales comotap
ycatchError
antes de que suceda algo realmente.Llamando a
subscribe(...)
activa la ejecución del observable y hace queHttpClient
componga y envíe la solicitud HTTP al servidor.Puede pensar en estos observables como blueprints para solicitudes HTTP reales.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-27 10:42:30