Angular2 HTTP POST请求

Nir*_*Nir 2 spring http angular

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

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');
  }
}
Run Code Online (Sandbox Code Playgroud)

我可以在dev-tools控制台中看到console.log(body)console.log(option)打印出来,但仅此而已:

铬开发工具

邮递员要求:

邮差要求

我的组件:

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);
  }
}
Run Code Online (Sandbox Code Playgroud)

我的组件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>
Run Code Online (Sandbox Code Playgroud)

Mat*_*att 9

http.get/post/...只要有人订阅Observable ,方法就会等待.在此之前它不会提出请求.这被称为a cold observable.订阅的工作原理如下:

http.get("http://yoururl.com").subscribe(data => { ... });
Run Code Online (Sandbox Code Playgroud)