Search code examples
angulartypescriptrxjsangular2-services

subscribe is not a function error thrown when trying to use JSON file in Angular 2


I'm trying to import a JSON file into my service and am receiving this error

Error: Uncaught (in promise): TypeError: this._qs.getBasicInfo(...).subscribe is not a function(…)

As of right now my service file looks like this

@Injectable()

export class QuestionService {

BasicInfoData: Observable<any>;

constructor(private http: Http){}

getBasicInfo() {
    this.BasicInfoData = this.http.get('app/questionnaire/questions.json').map(res =>
    res.json()).subscribe(data => this.BasicInfoData = data ) as Observable<any>

    return this.BasicInfoData;
    }

}

and my component looks like this

@Component({

    moduleId    : module.id,
    selector    : 'questionnaire-page',
    templateUrl : './questionnaire.component.html',
    providers   : [ QuestionService ]
})

export class QuestionnairePage implements OnInit, OnChanges {

    BasicInfo: Observable<any>;

    constructor(private _qs: QuestionService, private fbuild: FormBuilder) {}

    ngOnInit() {
        this._qs.getBasicInfo().subscribe( data => this.BasicInfo = data );
     console.log(this.BasicInfo);
    }

}

prior to trying to call the data from my service I had it working perfectly fine calling it directly into the ngOnInit() of my component like this

this.http.get('app/questionnaire/questions.json').subscribe(res => {
     this.Questions = res.json()
     console.log(this.Questions);
});

I started out trying to use this same thing and as I read, I added the Observable. I came across another post about RXJS saying their problem was subscribing directly to the data before it got there and their fix was to use .map() first then subscribe to that. It changed my error from an undefined error to the one I'm getting now so I figured that was a step in the right direction. I've been back and forth trying all sorts of things and it either creates another error indicating it breaks before this point or I just get the same error from the same snip of code. Why is this happening?


Solution

  • This code returns a Subscription

    getBasicInfo() {
        this.BasicInfoData = this.http.get('app/questionnaire/questions.json').map(res =>
        res.json()).subscribe(data => this.BasicInfo = data ) as Observable<any>
    
        return this.BasicInfoData;
        }
    }
    

    subscribe is a method of Observable not of Subscription. What you want is probably

    getBasicInfo() {
        return this.http.get('app/questionnaire/questions.json')
        .map(res => res.json());
    }
    

    this way an Observable is returned which can be subscribed to.