Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait for subscription in constructor of a Service

Tags:

angular

rxjs

In my service, I want to wait for until local variable baseurl is not initialized before making another http request.

Below is my service code:

@Injectable()
export class CoursesService  {
  baseUrl;
  constructor(private http: Http) {
    if(this.baseUrl != undefined){
      this.getJSON().subscribe(data =>
        this.baseUrl=data, 
        error => console.log(error)
      );
    }
}

public getJSON(): Observable<any> {
  return this.http.get("assets/apiDetails.json")
                  .map((res:any) => res.json());
}

getCourses(){
  return this.http.get(this.baseUrl+"/courses")
    .map((res:any) => res.json());
  }
}

As you can see getCourses method uses baseUrl variable, so When I will call getCourses method , I want to wait until baseUrl is not initialized.

I have tried to use ngOnInit but it not get called in Injectable type class.

like image 364
Amit Kumar Avatar asked Dec 14 '25 17:12

Amit Kumar


1 Answers

Make the baseUrl into an Observable that you share() (so many calls can use the same result - it's making the observable hot) and use in your other calls. Something like this should work:

import 'rxjs/add/operator/share';
import 'rxjs/add/operator/map'
import 'rxjs/add/operator/mergeMap'
// ...

@Injectable()
export class CoursesService {
  baseUrl$: Observable<string>;

  constructor(private http: Http) {
      this.baseUrl$ =
          this.getJSON()
              .share()
  }

  public getJSON(): Observable<any> {
      return this.http.get("assets/apiDetails.json")
         .map((res: any) => res.json());
  }

  getCourses(): Observable<YourCourseType[]> {
      return this.baseUrl$
          .mergeMap(url => {
              return this.http.get(url + "/courses")
                  .map((res: any) => res.json());
          });
  }
}
like image 174
Fredrik Lundin Avatar answered Dec 16 '25 18:12

Fredrik Lundin