Error using services and HttpClient with observables

3

I want to use services and HttpClient with observables, when using HttpClient without service everything works very well but when I pass it as a service I could not manage to use it.

Investigating I read that I should use observables in the service for later in the component to subscribe and bring the data. I have NOT been able to bring the response to the component, it is important to mention that I do not use http but HttpClient where I already get as Json (so that I do not get answers based on http ).

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders,HttpParams } from "@angular/common/http";
import { video, videosgeneral } from '../models/videos';
import { Observable } from 'rxjs/Rx';


@Injectable()
export class VideosService {
  videos: Array<video>;
  videoid: Array<video>;
  listavideos:Array<video>;
  public VideosApi = 'https://xxx.xxx.cl/api/v1/video';
  public token = 'xxxxxx';
  public paginas:number;

  constructor(public http: HttpClient) {  


  }

  getVideos(): Observable<any>{
    const headers = { 'Authorization': 'bearer xxxxxx' };
    const params = { 'page': '1' };  
    return this.http.get(this.VideosApi, { headers:headers, params });

  }



}

Component ts:

import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpParams, HttpEventType  } from "@angular/common/http";
import { video } from '../models/videos';
import { VideosService } from '../servicios/videos.service';
import { Observable } from 'rxjs/Rx';


@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss'],
  providers:[VideosService]
})
export class HomeComponent implements OnInit {
  public videosService:Array<any>;
  public listavideos:any;
  public videos: video[];

  constructor(private http : HttpClient, videoService: VideosService) {
    this.listavideos.getVideos().subscribe(
      data => {

          if(data.code != 200){
              console.log(data);
          }else{
            this.listavideos = data['videos']['data'];
            console.log(data['videos']['data']);
          }

      },
      error => {
          console.log(<any>error);
      }
  );


  }  


  ngOnInit() { 



  }


}

HTML component:

<div class="row"> 
      <div class="col s12 m4 l3" *ngFor="let video of listavideos"  id="{{video.vid}}">
        <div class="video">
          <div class="thumb">
            <div class="hover-efect"></div>
            <small class="time">{{video.duration}}</small>
            <a routerLink="/video"><img [src]="video.thumb" alt=""></a>
          </div>

          <div class="video-info">
            <a routerLink="/" class="title truncate">{{video.name}}</a>
            <a class="channel-name" routerLink="/">Categoria: {{video.category}}<span>
                          <i style="display:none;" class="material-icons">person</i></span></a>
            <span class="views">
              <i class="material-icons">visibility</i>{{video.total_views}} visitas
            </span>
            <span class="date">
              <i class="material-icons">access_time</i>{{video.begins}}
            </span>
          </div>

        </div>
      </div>
    </div>

ERROR:

  

Error: [object Object]       Stack trace:       resolvePromise @ webpack-internal: ///../../../../zone.js/dist/zone.js: 821: 31       resolvePromise @ webpack-internal: ///../../../../zone.js/dist/zone.js: 785: 17       scheduleResolveOrReject / < @ webpack-internal: ///../../../../zone.js/dist/zone.js: 870: 17       ZoneDelegate.prototype.invokeTask@webpack-internal: ///../../../../zone.js/dist/zone.js: 421: 17       onInvokeTask @ webpack-internal: ///../../../core/esm5/core.js: 4941: 24       ZoneDelegate.prototype.invokeTask@webpack-internal: ///../../../../zone.js/dist/zone.js: 420: 17       Zone.prototype.runTask@webpack-internal: ///../../../../zone.js/dist/zone.js: 188: 28       drainMicroTaskQueue @ webpack-internal: ///../../../../zone.js/dist/zone.js: 594: 25

    
asked by Gustavo Renjifo 22.02.2018 в 15:26
source

1 answer

2

Your component has several things wrong:

export class HomeComponent implements OnInit {
    public videosService: Array<any>; //esta variable no se usa para nada
    public listavideos: any; //no se inicializa
    public videos: video[];


    constructor(private http: HttpClient, videoService: VideosService) {
        //listavideos es undefined, es videoService lo que estás buscando
        this.listavideos.getVideos().subscribe(
            data => {

                if (data.code != 200) {
                    console.log(data);
                } else {
                    this.listavideos = data['videos']['data'];
                    console.log(data['videos']['data']);
                }

            },
            error => {
                console.log(<any>error);
            }
        );
    }

    ngOnInit() {
        //deberías hacer la petición aquí, no en el constructor
    }

}

The correct way to do it would be something like:

export class HomeComponent implements OnInit {

    public listavideos: video[];


    constructor(
        private http: HttpClient,
        private videoService: VideosService) { }

    ngOnInit() {
        this.videoService.getVideos().subscribe(
            data => {

                if (data.code != 200) {
                    console.log(data);
                } else {
                    this.listavideos = data['videos']['data'];
                    console.log(data['videos']['data']);
                }

            },
            error => {
                console.log(<any>error);
            }
        );
    }

}
    
answered by 22.02.2018 / 16:28
source