18
votes

In my angular2 app, I have service which send a get request to a url.

Here is my service:

    import {Http} from '@angular/http';
    import {Observable} from 'rxjs/Observable';
    import 'rxjs/add/operator/map';
    import {Injectable} from '@angular/core';
    import {Gallery} from './gallery';

    @Injectable()
    export class InstagramService{

        constructor(private _http:Http){

        }

        getGallery(username: string) : Observable<Gallery> {
            var result=this._http.get("https://www.instagram.com/"+username+"/media/").map(res => res.json());
 console.log(result);
        return result;
        }

    }

I have defined the return type as Observable<Gallery>, but it complains that:

A function whose declared type is neither 'void' nor 'any' must return a value

What is going wrong with this code?

1

1 Answers

19
votes

If you declare a return type, then why not return anything?

Usually this is what you want in this case.

getGallery(username: string) : Observable<Gallery> {
     return this._http.get("https://www.instagram.com/"+username+"/media/").map(res => res.json());
}

var result probably doesn't what you expect anyway because _http.get(...) returns an Observable not a value.

The caller of getGallery() can then subscribe to get notified when the value arrives.

instagramService.getGallery.subscribe((result) => this.galleryData = result);

When a value arrives then (result) => this.galleryData = result is called and the result is assigned to galleryData of your current component or service.