Reputation: 61
I am trying to use the OMDB api using fetch and I see in network that my database is working. However it doesn't show on my Angular 6 page. What am I missing in this code?
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class DataService {
constructor(private http: HttpClient) { }
getData() {
return fetch('http://www.omdbapi.com/?i=tt3896198&apikey=9fa6058b');
}
}
and this
import { DataService } from './../data.service';
import { Component, OnInit } from '@angular/core';
import {Observable} from 'rxjs';
@Component({
selector: 'app-movie-list',
templateUrl: './movie-list.component.html',
styleUrls: ['./movie-list.component.css']
})
export class MovieListComponent implements OnInit {
movies = [
{Title: 'Harry Potter'},
{Title: 'Space Jam'}
]
constructor(private data:DataService) { }
ngOnInit() {
// fetch('http://www.omdbapi.com/?i=tt3896198&apikey=9fa6058b')
// .then(response => response.json())
// .then( res => this.movies = res);
this.data.getData()
.then((response) => {response.json()
.then((data)=> {this.data = data;
});
});
}
and this
<p>
movie-list works!
</p>
<div class="card">
<ul>
<li *ngFor="let movie of movies">
<h2>{{movie.Title}}</h2>
<h3>{{movie.Plot}}</h3>
</li>
</ul>
</div>
And this is what I get ... see picture below.
What can I do to see the title and plot from the database??
Thank you for your help !
Upvotes: 1
Views: 1751
Reputation: 53
You haven't added the fetched data to your array of movies.
movies = [
{Title: 'Harry Potter'},
{Title: 'Space Jam'}]
This is why you are not seeing the desired data.
Edit: You could try and do this:
let movies = [];
function doFetch() {
fetch('http://www.omdbapi.com/?i=tt3896198&apikey=9fa6058b', {
method: "get"
}).then(function (response) {
return response.text();
}).then(function (text) {
let json = JSON.parse(text);
let data = { Title: json.Title, Plot: json.Plot }
movies.push(data);
});
}
doFetch();
This way you will populate your array with the data to display it later.
Upvotes: 1
Reputation: 50326
I think response.json()
has to go with the fetch
getData() {
return fetch('http://www.omdbapi.com/?i=tt3896198&apikey=9fa6058b')
.then((response) => {
response.json()
});
}
this.data.getData().then((data) => {
this.data = data;
});
Also the response is an object so you need to push the object to an array to use *ngFor
Upvotes: 1