[英]angular2 - cannot get data from web service
第一次学习打字稿和angular2。 我正在创建一个仅执行GET和POST的通用服务,以便可以在整个应用程序中使用它。 我已经基于Dynamic Forms中 Angular的示例创建了我的应用
我的问题是我的“ QuestionService”正在使用“ ServerService”,但它抱怨this.ServerService.getData is not a function
不是一个函数。
服务器服务
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class ServerService {
private apiUrl = 'app/users.json';
constructor (private http: Http) {}
getData (): Observable<any>[] {
return this.http.get(this.apiUrl)
.map(this.extractData)
.catch(this.handleError);
}
QuestionService
import { ServerService } from './server.service';
@Injectable()
export class QuestionService implements OnInit{
errorMessage: string;
mode = 'Observable';
questions: QuestionBase<any>[];
ServerService = ServerService;
ngOnInit() { this.getQuestions(); }
getQuestions(ServerService: ServerService<any>){
console.log('getQuestions');
console.log(this.ServerService.getData());
this.ServerService.getData()
.subscribe(
questions => this.questions = questions,
error => this.errorMessage = <any>error);
}
这是网址: https : //plnkr.co/edit/InWESfa6PPVKE0rXcSFG? p = preview
您需要做的是让Angular 将 ServerService
注入到QuestionService
,就像在ServerService
Http
一样
@Injectable()
export class QuestionService implements OnInit{
constructor(private serverService: ServerService) {}
ngOnInit() { this.getQuestions(); }
getQuestions(){
this.serverService.getData()
.subscribe(
questions => this.questions = questions,
error => this.errorMessage = <any>error);
}
}
然后,您需要将两个服务都添加到providers
数组
@NgModule({
imports: [HttpModule],
providers: [ServerService, QuestionService]
})
export class AppModule {}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.