简体   繁体   English

角度6:数据未显示在前端

[英]Angular 6 : Data are not displayed in front end

Hii : I am trying to display single data by id from api, here is what i have so far, Hii:我正在尝试通过api显示ID的单个数据,这是我到目前为止的内容,

api get method: api get方法:

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

here is service.ts 这是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);
  }

}

here is compo html: 这是compo 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>

an the last if needed structure of the data tested in 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
}

when I run my app the data are not displayed in front end what am I doing wrong here? 当我运行我的应用程序时,数据未显示在前端,这是我在做什么错? or what do I need to change , just learning guys :) thanks 或我需要改变什么,只是学习家伙:)谢谢

I think I know what the error is. 我想我知道错误是什么。

In getMovies you have this: getMovies您有以下内容:

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

But: 但:

  1. You're not using the id param at all. 您根本没有使用id参数。
  2. You're concatenating a variable and a string literal, not two variables 您是在连接一个变量和一个字符串文字,而不是两个变量

So, in the end, whichever the id is, you're making a request to http://localhost:8000moveUrl . 因此,最后,无论哪个id ,您都向http://localhost:8000moveUrl发出请求。 This is not a valid URL, and so the reason for the error you're getting. 这不是有效的URL,因此是出现错误的原因。

Change the code to: 将代码更改为:

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

This way you'll make requests to http://localhost:8000/movies/{id} , which is what you want. 这样,您便可以向http://localhost:8000/movies/{id}发出请求。

But you must learn to use the network tool. 但是您必须学习使用网络工具。 If you had done what I asked, you would have seen the error yourself. 如果您按照我的要求进行了操作,您将自己看到错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM