Angular:将通过API检索的JSON对象中的数组分配给变量

时间:2017-10-05 08:53:14

标签: javascript json angular

我正在努力通过Google Blogger API加载博客Feed并在组件中显示结果。我无法弄清楚如何将{“items”:[]}数组分配给posts变量以显示帖子。这就是我所拥有的:

组件:

import { Component, OnInit } from '@angular/core';
import { FeedService, Feed } from './feed.component.service';
import { Observable } from 'rxjs/Observable';

@Component({
selector: 'feed',
templateUrl: './feed.component.html',
styleUrls: ['./feed.component.scss']
})
export class FeedComponent implements OnInit {
    constructor(private feedService: FeedService){ }
    feed: Feed;
    posts: string[];

    ngOnInit(){
        this.feed = this.feedService.loadFeed();
        this.posts = this.feed['items'];
    }
}

服务:

import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { Feed } from './feed.component.service';

import 'rxjs/add/operator/map';

export interface Feed {
    [key: string]: any;
}

@Injectable()
export class FeedService {
    constructor(private http: Http){ }
    loadFeed(): Observable<Feed> {
        const headers = new Headers();
        headers.append('Content-Type', 'application/json');

        const options = new RequestOptions({ headers: headers });

        return this.http
            .get('https://www.googleapis.com/blogger/v3/blogs/3213900/posts?key=AIzaSyDDF7BymSIZjZKJ5x_FCLnV-GA1TbtIyNI', options)
            .map(response => response.json().data as Feed);
    }
}

和HTML(也使用Bootstrap 4):

<button class="btn back">Back</button>
<div class="header">
    <div class="container">
        <div class="row">
            <h1>feed</h1>
        </div>
    </div>
</div>
<div class="post">
    <div *ngFor="let post of posts">
        <h1> {{ post.title }} </h1>
        <p> {{ post.content }} </p>
    </div>
</div>
<div class="footer">
    <div class="container">
        <div class="row">
        </div>
    </div>
</div>

JSON返回一个键“items”:[]包含帖子的对象数组。每个帖子中都有标题和内容密钥。我无法显示任何帖子。非常感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

//here
this.feed = this.feedService.loadFeed();
this.posts = this.feed['items'];

你正在调用方法,因为它是同步调用。

this.feedService.loadFeed()返回一个Observable,您必须订阅该流并在可用时将数据分配给您的上下文。

this.feedService.loadFeed().subscribe(resp => this.posts = resp.items)