上面的错误是我得到的(指的是post请求中的subscribe方法的第二次调用。非常简单)在命令行之后"编译",我订阅了一个observable到获得对http请求的响应。没有服务(至少我创建的)正在其他文件夹中导入,据说post方法工作所需的一切。此外,我已经设置了模拟API,邮递员可以成功地获取和发送请求。
import { Component, OnInit } from '@angular/core';
import { Http, Response, RequestOptions, Headers } from '@angular/http';
import 'rxjs/add/operator/map';
import {Observable} from 'rxjs/Observable';
@Component({
selector: 'simple-http',
templateUrl: 'simple-http.component.html'
})
export class SimpleHttpComponent implements OnInit{
data: Object;
loading: boolean;
constructor(public http: Http) {
}
ngOnInit() {
}
getUser(): Object {
this.loading = true;
this.http.get('http://demo1495487.mockable.io/cort')
.subscribe((res: Response) => {
this.data = res.json();
this.loading = false;
console.log(this.data);
});
return this.data;
}
addUser(): void {
this.loading = true;
this.http.post('http://greenmachine.mockable.io/cortfield',
JSON.stringify({
body: 'bar',
title: 'foo',
userId: 1
}))
.suscribe((res: Response) => {
this.data = res.json();
console.log(this.data);
this.loading = false;
});
}
}

答案 0 :(得分:0)
当我查看您的代码时,我可以理解您的代码拼写错误。
从
更改您的代码 .suscribe((res: Response) => {
this.data = res.json();
console.log(this.data);
this.loading = false;
});
到
.subscribe((res: Response) => {
this.data = res.json();
console.log(this.data);
this.loading = false;
});
在订阅之前尝试映射到JSON。
this.http.post('http://greenmachine.mockable.io/cortfield',
JSON.stringify({
body: 'bar',
title: 'foo',
userId: 1
})).map((response: Response) => {
return <any>response.json();
}).subscribe((response: any) => {
this.data = response;
console.log(this.data);
this.loading = false;
});
或
this.http.post('http://greenmachine.mockable.io/cortfield',
JSON.stringify({
body: 'bar',
title: 'foo',
userId: 1
})).subscribe(result => this.data=result.json());