问题
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