[英]Typescript - A function whose declared type is neither 'void' nor 'any' must return a value
[英]A function whose declared type is neither 'void' nor 'any' must return a value
在我的 angular2 應用程序中,我有一個向 url 發送 get 請求的服務。
這是我的服務:
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;
}
}
我已將返回類型定義為Observable<Gallery>
,但它抱怨:
A function whose declared type is neither 'void' nor 'any' must return a value
這段代碼有什么問題?
如果你聲明了一個返回類型,那為什么不返回任何東西呢?
在這種情況下,通常這就是您想要的。
getGallery(username: string) : Observable<Gallery> {
return this._http.get("https://www.instagram.com/"+username+"/media/").map(res => res.json());
}
var result
可能不是你所期望的,因為_http.get(...)
返回一個Observable
而不是一個值。
然后getGallery()
的調用者可以訂閱以在值到達時收到通知。
instagramService.getGallery.subscribe((result) => this.galleryData = result);
當一個值到達時(result) => this.galleryData = result
被調用,並將result
分配給當前組件或服務的galleryData
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.