我在 Angular2 和 Spring-MVC 中构建一个应用程序,当我尝试向我的服务器发出 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)
and 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>