[英]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.