gxmad
gxmad

Reputation: 2210

how to create function that return Observable after verifications?

I want to return an http.get observable after checking if the token is valid and then getting the right url, at the end return a get observable. I wrote this code, but doesn't compile, 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)
    })
  })

}

code of tokenifyOsb method:

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

Upvotes: 3

Views: 2219

Answers (1)

Boris Lobanov
Boris Lobanov

Reputation: 2454

The error that you are getting means that you specified the return type for your method getListObs<T>(target):Observable<T> but you are not returning anything. Simply writing return this.tokenifyObs().subscribe(... will remove the typescript error. This however will return a subscription, not an Observable. You don't need to subscribe in this method, just return the observable. I haven't seen your entire code but I assume this is where you could start:

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

Upvotes: 3

Related Questions