Edon
Edon

Reputation: 1216

Retrieving object data from a service in Angular 2

I'm trying to retrieve data from my service function, but am running into issues. My LandingPage component code, shown below, sends a keystroke to my service function, which then returns an object full of data.

But I cannot get the service object to return to my LandingPage. Here is how I create my service:

task.service.ts

  addKey(keystroke) {
    const query = "https://api.themoviedb.org/3/search/tv?api_key=";
    fetch(query + key + '&language=en-US&query=' + keystroke)
      .then((show) => {
        show.json().then((obj) => {
          // grab the items we want from the response
          let resultItems = obj.results.map((show, index) => {
            return {
              id: show.id,
              poster: show.poster_path,
              rating: show.vote_average,
              backdrop: show.backdrop_path,
            };
          });
          // return our newly formed object
          return { data: resultItems }
        });
      });
  }

Here is where I am trying to receive the service data, in my:

landingpage.component.ts

  getKey(keystroke) {
      this.TaskService.addKey(keystroke)
        .subscribe(res => {
          this.shows = res.data; // trying to receive service info here
        });
  }

When I try to build, I receive the following error in my LandingPage component:

Property 'subscribe' does not exist on type 'void'.

I've tried using map instead of subscribe, but it returns a similar error.

How can I send the object result from my service, to my component?

Upvotes: 0

Views: 132

Answers (1)

0mpurdy
0mpurdy

Reputation: 3353

It looks like you're missing a return in your service method, I've also changed to using http from our discussion in the comments:

  addKey(keystroke): Observable<any> {
    const query = "https://api.themoviedb.org/3/search/tv?api_key=";
    return this.http.get(query + key + '&language=en-US&query=' + keystroke)
      .map(show => {
        show.json().then((obj) => {
          // grab the items we want from the response
          let resultItems = obj.results.map((show, index) => {
            return {
              id: show.id,
              poster: show.poster_path,
              rating: show.vote_average,
              backdrop: show.backdrop_path,
            };
          });
          // return our newly formed object
          return { data: resultItems }
        });
      });
  }

If you really want to use fetch you can if you:

  • Set the method return signature to Promise<any>
  • Use then instead of map in the service
  • Use then instead of subscribe in the component

Upvotes: 1

Related Questions