bier hier bier hier - 6 months ago 109
AngularJS Question

How to fix angular 2 error Cannot read property 'getOptional'?

I am getting my head around angular 2 and trying to define a service called searchservice and inject this in the bootstap part:

import {SearchService} from 'src/service';


This is what the service looks like:

import {Injectable} from 'angular2/core';
import {URLSearchParams, Jsonp} from 'angular2/http';

@Injectable()
export class SearchService {
constructor(private http: Http) {}

search (name: string) {
http.get('https://api.spotify.com/v1/search?q='+name.value+'&type=artist')
.map(response=>response.json());
}
}


However how can I fix this error that comes up when running the app?:

VM337 angular2-polyfills.js:138 Error: Cannot read property 'getOptional' of undefined
Error loading http://run.plnkr.co/fGkpQYXMc0eGUy6e/src/boot.ts
at _runAppInitializers (https://cdnjs.cloudflare.com/ajax/libs/angular.js/2.0.0-beta.0/angular2.dev.js:14832:25)
at PlatformRef_._initApp (https://cdnjs.cloudflare.com/ajax/libs/angular.js/2.0.0-beta.0/angular2.dev.js:14813:7)
at PlatformRef_.application (https://cdnjs.cloudflare.com/ajax/libs/angular.js/2.0.0-beta.0/angular2.dev.js:14768:22)
at Object.bootstrap (https://cdnjs.cloudflare.com/ajax/libs/angular.js/2.0.0-beta.0/angular2.dev.js:25054:64)
at execute (http://run.plnkr.co/fGkpQYXMc0eGUy6e/src/boot.ts!transpiled:60:23)
at u (https://rawgit.com/systemjs/systemjs/0.19.6/dist/system.js:5:97)
at Object.execute (https://rawgit.com/systemjs/systemjs/0.19.6/dist/system.js:5:3188)
at y (https://rawgit.com/systemjs/systemjs/0.19.6/dist/system.js:4:9948)
at w (https://rawgit.com/systemjs/systemjs/0.19.6/dist/system.js:4:10327)

plunkr ref:http://plnkr.co/edit/F6TSGfyRnR5jvbpiv2QJ?p=preview

Answer

The important part of the error is the line above the one you listed, which says:

Cannot resolve all parameters for SearchService(?). Make sure they all have valid type or annotations.

Your search service is trying to define a variable of type Http but you didn't import Http into the service.

change the import line to import {URLSearchParams, Jsonp, Http} from 'angular2/http';.

Comments