在我的服务中,我想等到本地变量baseurl未初始化,然后再发出另一个http请求.
以下是我的服务代码:
@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());
}
}
Run Code Online (Sandbox Code Playgroud)
正如你所看到的getCourses方法使用baseUrl变量,所以当我调用getCourses方法时,我想等到 baseUrl没有初始化.
我试过使用ngOnInit但它不会在Injectable类型类中调用.
让你baseUrl成为一个Observable你share()(这么多的电话可以使用相同的结果 - 它使可观察的热点)并在你的其他电话中使用.这样的事情应该有效:
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());
});
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4354 次 |
| 最近记录: |