我正在使用Http。
开发Angular 5在为应用程序提供服务时出现此错误..
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, ParamMap } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import 'rxjs/add/operator/switchMap';
@Component({
selector: 'app-post-detail',
templateUrl: './post-detail.component.html',
styleUrls: ['./post-detail.component.css']
})
export class PostDetailComponent implements OnInit {
body: string;
recent: {};
constructor(
private route: ActivatedRoute,
private router: Router,
private http: HttpClient,
) { }
ngOnInit() {
let id = this.route.snapshot.paramMap.get('id');
let userId = this.route.snapshot.paramMap.get('userid');
this.getUserPosts(userId);
this.http.get('https://jsonplaceholder.typicode.com/posts/'+id)
.subscribe((data)=>{
this.body = data.body;
});
}
}
我不知道为什么我收到此错误,并根据语法将类型指定为类中的字符串。
API的响应如下,
答案 0 :(得分:1)
(data)=>{
this.body = data.body;
}
data
不是json。您需要在.json()
上运行data
。或者您可以在订阅之前运行map
:
this.http.get('https://jsonplaceholder.typicode.com/posts/'+id)
.map(res => res.json())
.subscribe((data)=>{
this.body = data.body;
});
要使用map
,您需要导入它:
import 'rxjs/add/operator/map'
点击此处查看更多示例:https://angular.io/api/http/Http
修改强>:
输入响应 - 您需要为响应创建一个接口:
interface SomeResponse {
Body: SomeType;
}
并提出这样的请求:
this.http.get<SomeResponse>'https://jsonplaceholder.typicode.com/posts/'+id)
.subscribe((data)=>{
this.body = data.body;
});
此处有更多示例:https://codingthesmartway.com/angular-4-3-httpclient-accessing-rest-web-services-with-angular/