2016-07-29 190 views
2

我在Angular2和Spring-MVC中构建一个应用程序,当我尝试向我的服务器发出POST请求时,我没有得到任何成功或失败的迹象,但请求没有发生,因为我看不到新的数据。当我做Postman的请求时 - 请求成功,我可以看到新的数据。Angular2 HTTP POST请求

的Angular2代码:

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('http://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'); 
    } 
} 

我可以看到console.log(body)console.log(option)印在开发工具的控制台,但仅此而已,然后说:

chrome devtools

邮递员要求:

postman request

我的组件:

import { Component } from '@angular/core'; 

import { MainContentService } from '../shared/main-content.service'; 

@Component({ 
    moduleId: module.id, 
    selector: 'bfy-add-category', 
    templateUrl: 'add-category.component.html', 
    styleUrls: ['add-category.component.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代码:

<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> 
+0

请你发表您的HTML文件的代码以及 – rashfmnb

+0

@rashfmnb当然。我编辑问题并添加组件(打字稿)代码,它是html。还包括服务中的导入声明。为了清楚起见,在运行应用程序时,我没有在原子或终端中发现错误。所以我假设我正确导入一切。 – Nir

+0

@peeskillet此刻在我的本地计算机上运行的两个应用程序。如果我是一个CORS我假设我会在控制台中得到一个错误,但控制台很干净.. – Nir

回答

8

http.get/post/...方法等,只要有人预订了观测。在发生这种情况之前,它不会提出请求。这被称为cold observable。订阅作品像:

http.get("http://yoururl.com").subscribe(data => { ... }); 
+0

OMG我怎么会错过,谢谢先生! – Nir

+0

没关系,这并不像我从未偶然发现过自己。 :) – Matt