繁体   English   中英

Angular HTTP POST请求

[英]Angular HTTP POST request

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

我可以在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);
  }
}

我的组件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>

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM