我是Angular 2中的菜鸟。我正在开发一个简单的应用程序。我在Angular 2应用程序中使用服务时遇到问题。当我想在组件上使用它时,我不能在ngOnInit()组件方法上使用getFavoritos()服务方法。
节点控制台显示以下消息:
src / app / favoritos-list / favoritos-list.component.ts(30,31)中的错误:错误TS2339:类型'typeof FavoritosService'上不存在属性'getFavoritos'。
这是我的服务:
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');
}
}
);
}
}
提前致谢
我在这个链接中找到了解决方案:
https://www.reddit.com/r/Angular2/comments/6ovswj/property_get_does_not_exist_on_type_typeof/
在我放置的组件构造函数上:
private _favoritoService = FavoritosService;
代替:
private _favoritoService : FavoritosService;
我使用像TSLint这样的Angular 2插件编写Visual Studio代码。我很惊讶这个IDE在这一行中没有显示任何错误