javascript - Angular 6 : Data are not displayed in front end

标签 javascript node.js html typescript express

嗨:我正在尝试通过 api 中的 id 显示单个数据,这是我到目前为止所拥有的,

api获取方法:

  app.get('/movies/:id', (req, res) => {
        const id =req.params.id;
        request('https://api.themoviedb.org/3/movie/'+id+'?&api_key=2931998c3a80d7806199320f76d65298', function (error, response, body) {
            console.log('error:', error); // Print the error if one occurred and handle it
            console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
            res.send(body)
        });
    });

compo.ts

import { Component, OnInit} from '@angular/core';
import { MoviesService } from '../movies.service';
import { RouterModule, Routes } from '@angular/router';
import {ActivatedRoute} from '@angular/router';

@Component({
  selector: 'app-movie',
  templateUrl: './movie.component.html',
  styleUrls: ['./movie.component.scss']
})
export class MovieComponent implements OnInit {
  movie: object;
  constructor(private router: ActivatedRoute, private moviesService: MoviesService){}

  ngOnInit() {
    this.router.params.subscribe((params) => {
      // tslint:disable-next-line:prefer-const
      let id = params['id'];
      this.moviesService.getMovies(id)
      .then((movie: any) => {
        console.log(movie);
        this.movie = movie.results;
    });
   });
  }
  }
}

这里是service.ts

import { Injectable } from '@angular/core';
import { Headers, Http, Response } from '@angular/http';
import { Jsonp } from '@angular/http';

@Injectable({
  providedIn: 'root'
})
export class MoviesService {
  moveUrl = '/movies/';
  private apiUrl = 'http://localhost:8000';
  constructor(private http: Http, private _jsonp: Jsonp) { }

    getMovie(id: string): Promise<any> {
    return this.http.get(this.apiUrl + 'moveUrl')
      .toPromise()
      .then(this.handleData)
      .catch(this.handleError);
  }

}

这是 html 组合:

<div *ngIf="movie">
  <div class="panel panel-default">
<div class="panel-heading">
  <h3 class="panel-title">{{movie.title}} </h3>
</div>
<div class="panel-body">
  <div class="row">
      <div class="col-md-5">
          <img class="thumbnail" src="http://image.tmdb.org/t/p/w500/{{movie.poster_path}}">
      </div>
      <div class="col-md-7">
          <ul class="list-group">
              <li class="list-group-item">Genres: <span *ngFor="let genre of movie.genres">{{genre.name}}, </span></li>    
              <li class="list-group-item">Release Date: {{movie.release_date}}</li> 
          </ul>
          <br>
          <a *ngIf="movie.homepage" href="{{movie.homepage}}" target="_blank" class="btn btn-default zero">Visit Movie Website</a>
      </div>
  </div>
</div>
</div>   
</div>

在 postman 中测试的数据的最后一个(如果需要)结构:

{
    "adult": false,
    "backdrop_path": "/gBmrsugfWpiXRh13Vo3j0WW55qD.jpg",
    "belongs_to_collection": {
        "id": 328,
        "name": "Jurassic Park Collection",
        "poster_path": "/qIm2nHXLpBBdMxi8dvfrnDkBUDh.jpg",
        "backdrop_path": "/pJjIH9QN0OkHFV9eue6XfRVnPkr.jpg"
    },
    "budget": 260000000,
    "genres": [
        {
            "id": 28,
            "name": "Action"
        },
        {
            "id": 12,
            "name": "Adventure"
        },
        {
            "id": 878,
            "name": "Science Fiction"
        }
    ],
    "homepage": "http://www.jurassicworld.com/",
    "id": 351286,
    "imdb_id": "tt4881806",
    "original_language": "en",
    "original_title": "Jurassic World: Fallen Kingdom",
    "overview": "A volcanic eruption threatens the remaining dinosaurs on the island of Isla Nublar, where the creatures have freely roamed for several years after the demise of an animal theme park known as Jurassic World. Claire Dearing, the former park manager, has now founded the Dinosaur Protection Group, an organization dedicated to protecting the dinosaurs. To help with her cause, Claire has recruited Owen Grady, a former dinosaur trainer who worked at the park, to prevent the extinction of the dinosaurs once again.",
    "popularity": 250.012321,
    "poster_path": "/c9XxwwhPHdaImA2f1WEfEsbhaFB.jpg",
    "production_companies": [
        {
            "id": 56,
            "logo_path": "/cEaxANEisCqeEoRvODv2dO1I0iI.png",
            "name": "Amblin Entertainment",
            "origin_country": "US"
        },
        {
            "id": 8111,
            "logo_path": null,
            "name": "Apaches Entertainment",
            "origin_country": ""
        },
        {
            "id": 923,
            "logo_path": "/5UQsZrfbfG2dYJbx8DxfoTr2Bvu.png",
            "name": "Legendary Entertainment",
            "origin_country": "US"
        },
        {
            "id": 103204,
            "logo_path": null,
            "name": "Perfect World Pictures",
            "origin_country": "US"
        },
        {
            "id": 33,
            "logo_path": "/8lvHyhjr8oUKOOy2dKXoALWKdp0.png",
            "name": "Universal Pictures",
            "origin_country": "US"
        }
    ],
    "production_countries": [
        {
            "iso_3166_1": "US",
            "name": "United States of America"
        }
    ],
    "release_date": "2018-06-06",
    "revenue": 0,
    "runtime": 128,
    "spoken_languages": [
        {
            "iso_639_1": "en",
            "name": "English"
        }
    ],
    "status": "Released",
    "tagline": "The park is gone",
    "title": "Jurassic World: Fallen Kingdom",
    "video": false,
    "vote_average": 6.7,
    "vote_count": 642
}

当我运行我的应用程序时,数据没有显示在前端,我在这里做错了什么?或者我需要改变什么,只是学习人员:)谢谢

最佳答案

我想我知道错误是什么。

getMovies中你有这个:

return this.http.get(this.apiUrl + 'moveUrl')

但是:

  1. 您根本没有使用 id 参数。
  2. 您连接的是一个变量和一个字符串文字,而不是两个变量

因此,最终,无论 id 是什么,您都会向 http://localhost:8000moveUrl 发出请求。这不是有效的 URL,因此也是您收到错误的原因。

将代码更改为:

return this.http.get(this.apiUrl + moveUrl + id)
      .toPromise()
      .then(this.handleData)
      .catch(this.handleError);

这样您就可以向 http://localhost:8000/movies/{id} 发出请求,这就是您想要的。

但是你必须学会​​使用网络工具。如果您按照我的要求进行操作,您自己就会看到该错误。

关于javascript - Angular 6 : Data are not displayed in front end,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50889616/

相关文章:

javascript - HH :MM with Moment. js(或没有)的小时数

javascript - 按住按钮连续滚动 ReactJS

javascript - HTML 标记 : Write elements textContent via attribute instead of via passing the value as a child?

javascript - Electron App - 将主进程分成几个文件并共享变量

javascript - 我的 WebDriver 脚本可以从网页捕获事件吗?

javascript - 基于多个标准对多维数组进行排序

php - 在 while 循环中使用 foreach 循环并回显值

node.js - module.export 函数不返回结果

node.js - 使用 Azure cosmos DB 进行表达

javascript - 抓取一组包含混合内容的页面的最佳方法