我想在检查令牌是否有效然后获取正确的URL后返回一个http.get observable,最后返回一个get observable。我编写了这段代码,但没有编译,error : A function whose declared type is neither 'void' nor 'any' must return a value.
getListObs<T>(target):Observable<T>{
this.tokenifyObs().subscribe(
token => {
console.log("get list of objects ")
return Observable.create(observer => {
let myUrl = this.urls_list[this.baseUrl] + this.urls_list[target];
observer.next(myUrl);
})
.subscribe( (myUrl)=>{
return this.http.get<T[]>(myUrl)
})
})
}
tokenifyOsb方法的代码:
tokenifyObs():Observable<String>{
return Observable.create(observer => {
console.log("checking token.. ")
if(! this.token){
let token = sessionStorage.getItem("token")
this.token = token
this.header.headers["authorization"] = this.auth + token;
this.validAuth = true
}
console.log("token is : ", this.token)
observer.next(this.token);
})
}
答案 0 :(得分:3)
您获得的错误意味着您为方法getListObs<T>(target):Observable<T>
指定了返回类型,但您没有返回任何内容。只需编写return this.tokenifyObs().subscribe(...
即可删除打字稿错误。然而,这将返回订阅,而不是Observable。您不需要订阅此方法,只需返回observable即可。我还没有看到你的整个代码,但我认为这是你可以开始的地方:
getListObs<T>(target):Observable<T>{
return this.tokenifyObs()
.switchMap(token => { // you are not using token anywhere so you can replace it with ()
let myUrl = this.urls_list[this.baseUrl] + this.urls_list[target];
return this.http.get<T>(myUrl);
});
}