在我的angular2应用中,我有服务向网址发送获取请求。
这是我的服务:
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
这段代码出了什么问题?
答案 0 :(得分:9)
如果您声明了返回类型,那么为什么不返回任何内容?
在这种情况下,通常这就是你想要的。
R version 3.2.2 (2015-08-14)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows Server 2012 x64 (build 9200)
locale:
[1] LC_COLLATE=English_United States.1252 LC_CTYPE=English_United States.1252
[3] LC_MONETARY=English_United States.1252 LC_NUMERIC=C
[5] LC_TIME=English_United States.1252
attached base packages:
[1] parallel stats graphics grDevices utils datasets methods base
other attached packages:
[1] doParallel_1.0.10 iterators_1.0.8 earth_4.4.4 plotmo_3.1.4 TeachingDemos_2.10
[6] plotrix_3.6-2 glmnet_2.0-5 foreach_1.4.3 Matrix_1.2-4 caretEnsemble_2.0.0
[11] caret_6.0-64 ggplot2_2.1.0 RevoUtilsMath_8.0.1 RevoUtils_8.0.1 RevoMods_8.0.1
[16] RevoScaleR_8.0.1 lattice_0.20-33 rpart_4.1-10
loaded via a namespace (and not attached):
[1] Rcpp_0.12.4 compiler_3.2.2 nloptr_1.0.4 plyr_1.8.3 tools_3.2.2
[6] lme4_1.1-11 digest_0.6.9 nlme_3.1-126 gtable_0.2.0 mgcv_1.8-12
[11] SparseM_1.7 gridExtra_2.2.1 stringr_1.0.0 MatrixModels_0.4-1 stats4_3.2.2
[16] grid_3.2.2 nnet_7.3-12 data.table_1.9.6 pbapply_1.2-1 minqa_1.2.4
[21] reshape2_1.4.1 car_2.1-2 magrittr_1.5 scales_0.4.0 codetools_0.2-14
[26] MASS_7.3-45 splines_3.2.2 pbkrtest_0.4-6 colorspace_1.2-6 quantreg_5.21
[31] stringi_1.0-1 munsell_0.4.3 chron_2.3-47
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
。