在服务的构造函数中等待订阅 [英] Wait for subscription in constructor of a Service

查看:41
本文介绍了在服务的构造函数中等待订阅的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的服务中,我要等到本地变量 baseurl 未初始化后再发出另一个http请求.

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

以下是我的服务代码:

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

如您所见, getCourses 方法使用了 baseUrl 变量,因此当我调用 getCourses 方法时,我想等到baseUrl 未初始化.

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.

我尝试使用 ngOnInit ,但是在 Injectable 类型类中未调用它.

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

推荐答案

baseUrl 设为您 share() Observable (如此多的呼叫可以使用相同的结果-这使得可观察的 )并在您的其他通话中使用.这样的事情应该起作用:

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

这篇关于在服务的构造函数中等待订阅的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆