Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

angular

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());
    }

}

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?

like image 637
Jeff Avatar asked Aug 08 '16 19:08

Jeff


1 Answers

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.

like image 88
Günter Zöchbauer Avatar answered Oct 19 '22 10:10

Günter Zöchbauer