Wait for subscription in constructor of a Service

假装没事ソ 提交于 2019-12-23 23:04:14

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/46484310/wait-for-subscription-in-constructor-of-a-service

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!