Hot Zellah
Hot Zellah

Reputation: 1081

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,

api get method:

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

here is 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:

<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

Upvotes: 0

Views: 1761

Answers (1)

Oscar Paz
Oscar Paz

Reputation: 18302

I think I know what the error is.

In getMovies you have this:

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

But:

  1. You're not using the id param at all.
  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. This is not a valid URL, and so the reason for the error you're getting.

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.

But you must learn to use the network tool. If you had done what I asked, you would have seen the error yourself.

Upvotes: 1

Related Questions