0
我修改了快速入門教程,從以下URL獲取帖子集合:https://jsonplaceholder.typicode.com/posts,但我只能看到默認的初始化值,而不是來自服務器的實際值。Angular2解析HTTP響應
其中一個元件的樣子:
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}
該目的被表示爲一個郵政類定義如下:
export class Post
{
userId: number;
id: number;
title: string;
body: string;
}
服務返回可觀察到的郵[]
import { Post } from './post'
@Injectable()
export class PostService{
private postUrl = 'https://jsonplaceholder.typicode.com/posts';
constructor (private http: Http) {}
public getPosts(): Observable<Post[]> {
return this.http.get(this.postUrl)
.map(this.extractData);
}
private extractData(res: Response) {
let body = res.json();
return body.data || { };
}
的
然後,Component訂閱Observable以獲取數組並設置其屬性:
import { Post } from './post'
import { PostService } from './postservice.service'
@Component({
selector:'mi-comp',
template: `<h1>Embedded Component</h1>
<ul>
<li *ngFor="let post of posts">
{{post.id }} {{post.title }}
</li>
</ul>
`,
providers: [PostService]
})
export class MiComponente
{
posts: Post[] =
[{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
},
{
"userId": 1,
"id": 2,
"title": "qui est esse",
"body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
},
{
"userId": 1,
"id": 3,
"title": "ea molestias quasi exercitationem repellat qui ipsa sit aut",
"body": "et iusto sed quo iure\nvoluptatem occaecati omnis eligendi aut ad\nvoluptatem doloribus vel accusantium quis pariatur\nmolestiae porro eius odio et labore et velit aut"
}];
errorMessage: string;
counter = 0;
constructor(private postService: PostService){
this.postService.getPosts()
.subscribe(
posts => this.posts = posts,
error => this.errorMessage = <any>error);
}
如果我改變服務的提取函數以返回body.data,我會看到默認值一秒鐘,然後是空的。我已經調試了這個響應,我可以看到那裏有100個元素的數組。
此外,如果我將所有內容從Post改爲string,我可以在屏幕上看到100個對象的列表。
您是否嘗試過剛剛返回'body'從'extractData',而不是'body.data '?看[文檔](https://angular.io/docs/ts/latest/guide/server-communication.html#!#parse-to-json)它注意到他們的服務器被設置爲返回值在一個數據對象中,但是*「[n]所有服務器都返回一個帶有數據屬性的對象。」* –
是的,返回body而不是body.data! –