首页 > 解决方案 > 使用 fetch 添加 Omdb Api?

问题描述

我正在尝试通过 fetch 使用 OMDB api,并且我在网络中看到我的数据库正在运行。但是它没有显示在我的 Angular 6 页面上。我在这段代码中缺少什么?

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

和这个

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

和这个

<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>

这就是我得到的......见下图。

在此处输入图像描述

我该怎么做才能从数据库中查看标题和情节?

谢谢您的帮助 !

标签: javascriptdatabaseangularfetch

解决方案


我认为response.json()必须与fetch

getData() {
  return fetch('http://www.omdbapi.com/?i=tt3896198&apikey=9fa6058b')
    .then((response) => {
      response.json()
    });
}

this.data.getData().then((data) => {
  this.data = data;
});

响应也是一个对象,因此您需要将对象推送到数组中才能使用*ngFor

演示


推荐阅读