javascript - 使用 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>
这就是我得到的......见下图。
我该怎么做才能从数据库中查看标题和情节?
谢谢您的帮助 !
解决方案
我认为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
推荐阅读
- python - 如何在 docker 上的 Jenkins 中设置 PYTHONPATH
- c++ - C ++无法插入空向量
- scala - 如何避免在Scala的Spark RDD中使用collect?
- python - 如何使用 python webdriver 在此文本框中书写?
- scala - Play Framework 2.5:未定义 trait Filter 类型 => akka.stream.Materializer 中的方法 mat
- paypal - 验证订单 ID 是否存在
- angular - Webpack 生成 SCSS 源映射但不生成 JS
- postgresql - 连接到 Postgres 的 Kotlin 错误:org.postgresql.util.PSQLException:发生异常情况导致驱动程序失败
- node.js - 如何在使用 Google Drive API v3 移动文件之前检查文件是否已完成上传?
- javascript - 为什么 react-select 不适用于状态选项?