Angular: assign an array from a JSON object received via API to a variable

I am working on uploading a blog feed via the Google Blogger API and displaying the results in a component. I cannot figure out how to assign the array {"items": []} to the posts variable to display posts. Here is what I have:

component:

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'];
    }
}

Service:

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);
    }
}

and HTML (also using 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 is returned with the key "elements": [], which contains an array of objects for messages. Each column has a title and a content key. I can not receive messages. Any help is appreciated.

+6
source share
1 answer
//here
this.feed = this.feedService.loadFeed();
this.posts = this.feed['items'];

you call the method since it was a synchronous call.

this.feedService.loadFeed() Observable, .

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

All Articles