我是 Angular 2 的菜鸟。我正在开发一个简单的应用程序。我在 Angular 2 应用程序中使用服务时遇到问题。当我想在组件上使用它时,我不能在 ngOnInit() 组件方法上使用 getFavoritos() 服务方法。
节点控制台显示此消息:
src/app/favoritos-list/favoritos-list.component.ts(30,31) 中的错误:错误 TS2339:“typeof FavoritosService”类型上不存在属性“getFavoritos”。
这是我的服务:
收藏夹.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()) ;
}
}
这是我的组件:
收藏夹列表.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');
}
}
);
}
}
提前致谢