Angular HTTP POST request

2019-05-27 11:51发布

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.

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

I can see the console.log(body) and console.log(option) printed in the dev-tools console, but nothing more then that:

chrome devtools

The postman request:

postman request

My component:

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);
  }
}

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>

1条回答
Evening l夕情丶
2楼-- · 2019-05-27 12:11

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("http://yoururl.com").subscribe(data => { ... });
查看更多
登录 后发表回答