Web services angular2-无法从web服务获取数据
第一次学习打字稿和angular2。我正在创建一个通用的服务,它只需要GET和POST,这样我就可以在整个应用程序中使用它。我的应用程序基于Angular的示例 我的问题是,我的“QuestionService”使用的是“ServerService”,但它抱怨Web services angular2-无法从web服务获取数据,web-services,angular,angular2-observables,Web Services,Angular,Angular2 Observables,第一次学习打字稿和angular2。我正在创建一个通用的服务,它只需要GET和POST,这样我就可以在整个应用程序中使用它。我的应用程序基于Angular的示例 我的问题是,我的“QuestionService”使用的是“ServerService”,但它抱怨this.ServerService.getData不是函数不是函数 服务器服务 import { Injectable } from '@angular/core'; import { Http, Response } from
this.ServerService.getData不是函数
不是函数
服务器服务
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);
}
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);
}
从'@angular/core'导入{Injectable};
从'@angular/Http'导入{Http,Response};
从“rxjs/Observable”导入{Observable};
@可注射()
导出类服务器服务{
私有apiUrl='app/users.json';
构造函数(私有http:http){}
getData():Observable您需要做的是将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);
}
}
@NgModule({
imports: [HttpModule],
providers: [ServerService, QuestionService]
})
export class AppModule {}