我在Angular2和Spring-MVC中构建了一个应用程序,当我尝试向我的服务器发出POST请求时,我没有任何成功或失败的迹象,但请求没有发生,因为我不能看到新数据。当我收到邮递员的请求时 - 请求成功,我可以看到新数据。
I build an app in Angular2 and Spring-MVC, and when I try to make a POST request to my server I don't get any sign of success or fail, but the request doesn't happening because I can't see the new data. When I do the request from Postman - the request is successful and I can see the new data.
Angular2代码:
The Angular2 code:
import { Injectable } from '@angular/core'; import { Http, Response, Headers, RequestOptions } from '@angular/http'; import { Observable } from 'rxjs/Rx'; import 'rxjs/add/operator/map'; @Injectable() export class MainContentService { constructor( private http: Http) {} addNewCategory(categoryName: string) { let body = JSON.stringify({ name: categoryName }); let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); console.log(body); console.log(options); return this.http.post('localhost:8080/api/v1/categories', body, options) .map(this.extractData) .catch(this.handleError); } private extractData(res: Response) { let body = res.json(); console.log(body); return body.data || { }; } private handleError (error: any) { console.error(error); return Observable.throw(error.json().error || 'Server error'); } }我可以看到控制台.log(正文)和 console.log(选项)在dev-tools控制台中打印,但仅此而已:
I can see the console.log(body) and console.log(option) printed in the dev-tools console, but nothing more then that:
邮递员请求:
我的组件:
import { Component } from '@angular/core'; import { MainContentService } from '../shared/main-content.service'; @Component({ moduleId: module.id, selector: 'bfy-add-category', templateUrl: 'add-categoryponent.html', styleUrls: ['add-categoryponent.css'], providers: [MainContentService] }) export class AddCategoryComponent { editName: string; constructor( private mainContentService: MainContentService ) { } cancel() { console.log('cencel'); } save() { let categoryName = this.editName; this.mainContentService.addNewCategory(categoryName); } }我的组件HTML代码:
My component HTML code:
<div class="col-sm-12 col-md-8 col-lg-9 thumbnail pull-right"> <label>Category: </label> <input [(ngModel)]="editName" placeholder="Category name .."/> <div> <button (click)="cancel()">Cancel</button> <button (click)="save()">Save</button> </div> </div>推荐答案
http.get / post /...方法等待有人订阅Observable。在此之前它不会提出请求。这称为冷可观察。订阅的工作原理如下:
The http.get/post/... methods wait as long as someone subscribes to the Observable. It won't make a request before that happens. This is called a cold observable. Subscribing works like that:
http.get("yoururl").subscribe(data => { ... });更多推荐
Angular2 HTTP POST请求
发布评论