角度 2:属性"suscribe"在类型"可观察"上不存在<Response>



上面的错误是我得到的(指的是post请求中订阅方法的第二次调用。非常简单(在"编译"后的命令行中,我订阅了一个可观察量以获得对 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;
});
}

}

当我查看您的代码时,我可以理解您在代码上的拼写错误。

将代码从

.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());

最新更新