2016-07-29 331 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