在完成教程之后,我试图在组件中注入服务:
import { Component } from '@angular/core';
import { TodoService } from './todos.service';
import { ITodo } from './todo';
import { Http , Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
@Component({
selector: 'my-app',
templateUrl: `app/app.component.html`,
providers: [TodoService]
})
export class AppComponent
{
itodos: ITodo[];
appTitle: string = 'To Do App';
constructor(private _todo: TodoService);
ngOnInit() : void {
this._todo.gettodos()
.subscribe(itodos => this.itodos = itodos);
}
}
在调用TodoService时,出现“缺少构造函数实现”
我的服务:
import { Injectable } from '@angular/core';
import { Http , Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';
import { ITodo } from './todo';
@Injectable()
export class TodoService {
private _todoUrl='app/todos.json';
constructor(private _http: Http){}
gettodos(): Observable<ITodo[]> {
return this._http.get(this._todoUrl)
.map((response: Response) => <ITodo[]> response.json())
.do(data => console.log(JSON.stringify(data)));
}
}
由于我的TodoService使用Http,我该怎么做才能清除错误?
答案 0 :(得分:5)
您的构造函数没有主体,如果您不想在构造函数中有任何多余的代码,只需提供一个空主体
constructor(private _todo: TodoService){}