1

I'm trying to make a simple HTTP request using Angular, but I keep getting this error:

Property 'http' does not exist on type 'WorksService'.

import {Injectable}     from 'angular2/core';
import {Http, HTTP_PROVIDERS, Response} from 'angular2/http';
import {Observable}     from 'rxjs/Observable';

export class Work {

  constructor(public id: number, public name: string) { }

}


@Injectable()
export class WorksService {

 constructor (private http: Http) {}

 private _WorksUrl = 'api/projects';  // URL to web api

 getHeroes () {
  return this.http.get(this._WorksUrl)
                .map(res => <Work[]> res.json().data)
                .catch(this.handleError);
 }
 private handleError (error: Response) {
   // instead of just logging it to the console
   console.error(error);
   return Observable.throw(error.json().error || 'Server error');
  }
}
1
  • How are you creating WorksService? Where does the object come from? Commented Mar 23, 2016 at 21:48

1 Answer 1

1

I guess that you instantiate the service by your own. You need to get it through dependency injection so Angular2 will provide the http instance directly.

To do that, just add the service in providers either when bootstrapping your application or within the providers attribute of the component that uses the service (directly or indirectly).

bootstrap(AppComponent, [ HTTP_PROVIDERS, WorksService ]);

or

bootstrap(AppComponent, [ HTTP_PROVIDERS ]);

(...)

@Component({
  (...)
  providers: [ WorksService ]
})
export class SomeComponent {}

To inject it then, you do like this:

@Component({
  (...)
})
export class SomeComponent {
  constructor(private service WorksService) {
    this.service.getHeroes().subscribe(
      (data) => {
        (...)
      });
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.