angular2-servicesangular2-componentsangular2-injection

Angular 2 component inject service: "[ts] Property doesn't exist on the type"


I am noob in Angular 2. I am developing a simple app. I have a problem when I use a service in a Angular 2 app. When I want use it on a component, I can't use the getFavoritos() service method on ngOnInit() component method.

Node console shows this messagge:

ERROR in src/app/favoritos-list/favoritos-list.component.ts(30,31): error TS2339: Property 'getFavoritos' does not exist on type 'typeof FavoritosService'.

This is my service:

favoritos.service.ts

import { Settings } from './../settings/settings';
import { Favorito } from './../models/favorito';
import { Injectable } from '@angular/core';
import { Http, Response, Headers } from '@angular/http';
import 'rxjs/add/operator/map' ;
import {Observable} from 'rxjs/Observable';

@Injectable()
export class FavoritosService {

 public url: string;

 constructor(private _http: Http) {
   this.url = Settings.GET_FAVORITOS;
 }

 getFavoritos() {
   return this._http.get(this.url)
      .map( res => res.json()) ;
 }
}

This is my component:

favoritos-list.component.ts

import { Favorito } from './../models/favorito';
import { FavoritosService } from './../service/favoritos.service'; 
import { Component, OnInit} from '@angular/core'; 

@Component({
   providers : [FavoritosService], 
   selector: 'app-favoritos-list',
   templateUrl: './favoritos-list.html',
   styleUrls: ['./favoritos.css']
})

export class FavoritosListComponent implements OnInit {
   public title: string;
   public errorMessage;


   constructor(       
      private _favoritoService = FavoritosService;        
   ) {
      this.title = 'Listado de marcadores:';
   }

   ngOnInit() {
      console.log('Favoritos list cargando...');
      this._favoritoService.getFavoritos().subscribe(
         //Compiler doesn't recognize getFavoritos()            
         result => {
            console.log(result);
         },
         error => {
            this.errorMessage = <any>error;
            if (this.errorMessage != null) {
                console.log(this.errorMessage);
                alert('Error en la petición');
            }
         }
     );
  }
 }

Thanks in advance


Solution

  • I found out the solution in this link:

    https://www.reddit.com/r/Angular2/comments/6ovswj/property_get_does_not_exist_on_type_typeof/

    On the component constructor I put:

    private _favoritoService = FavoritosService;    
    

    Instead of:

    private _favoritoService : FavoritosService;    
    

    I use to coding Visual Studio Code with Angular 2 plugins like TSLint. I am very surprised this IDE doesn´t show any error in this line