angular2 - 无法从 Web 服务获取数据 [英] angular2 - cannot get data from web service
问题描述
学习打字稿&angular2 第一次.我正在创建一个只执行 GET 和 POST 的通用服务,以便我可以在整个应用程序中使用它.我的应用程序基于 Dynamic Forms 中的 Angular 示例
Learning typescript & angular2 for the first time. I'm creating a generic service that just does GET and POST so that I can use it in the entire app. I've based my app on Angular's example from Dynamic Forms
我的问题是我的QuestionService"正在使用ServerService",但它抱怨this.ServerService.getData 不是函数
不是函数.
My issue is that my "QuestionService" is using a "ServerService" but it is complaining that this.ServerService.getData is not a function
isnt 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);
}
问题服务
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=预览
推荐答案
你需要做的是让Angular注入ServerService
到QuestionService中code>,就像在
ServerService
What you need to do is let Angular inject the ServerService
into the QuestionService
, just like are doing with the Http
inside the ServerService
@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
数组
Then you need to add both services to the providers
array
@NgModule({
imports: [HttpModule],
providers: [ServerService, QuestionService]
})
export class AppModule {}
这篇关于angular2 - 无法从 Web 服务获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!