【问题标题】:Angular 2 component inject service: "[ts] Property doesn't exist on the type"Angular 2 组件注入服务:“类型上不存在 [ts] 属性”
【发布时间】:2017-12-24 16:55:23
【问题描述】:

我是 Angular 2 的菜鸟。我正在开发一个简单的应用程序。 我在 Angular 2 应用程序中使用服务时遇到问题。 当我想在组件上使用它时,我不能在 ngOnInit() 组件方法上使用 getFavoritos() 服务方法。

节点控制台显示此消息:

src/app/favoritos-list/favoritos-list.component.ts(30,31) 中的错误: 错误 TS2339:类型“typeof”上不存在属性“getFavoritos” FavoritosService'。

这是我的服务:

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

这是我的组件:

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

提前致谢

【问题讨论】:

    标签: angular2-services angular2-components angular2-injection


    【解决方案1】:

    我在这个链接中找到了解决方案:

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

    在我放的组件构造函数上:

    private _favoritoService = FavoritosService;    
    

    代替:

    private _favoritoService : FavoritosService;    
    

    我习惯于使用 Angular 2 插件(如 TSLint)编写 Visual Studio Code。我很惊讶这个 IDE 在这一行没有显示任何错误

    【讨论】:

      猜你喜欢
      • 2017-02-13
      • 1970-01-01
      • 2018-05-01
      • 1970-01-01
      • 2021-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-11
      相关资源
      最近更新 更多