angular2 - cannot get data from web service

可紊 提交于 2020-01-06 19:39:28

问题


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

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.

ServerService

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);
    }

Here is the url: https://plnkr.co/edit/InWESfa6PPVKE0rXcSFG?p=preview


回答1:


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);
    }
}

Then you need to add both services to the providers array

@NgModule({
  imports: [HttpModule],
  providers: [ServerService, QuestionService]
})
export class AppModule {}


来源:https://stackoverflow.com/questions/41092825/angular2-cannot-get-data-from-web-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!