【问题标题】:Angular 2 wait until variable setAngular 2等到变量设置
【发布时间】:2017-11-29 10:57:50
【问题描述】:

我需要通过http.get 获取变量的值(必须是异步的):

@Injectable()
export class interaction{
private host: string="";
private port: string = "";
constructor(private http: Http) {

    this.http.get("/interaction.json").subscribe((data: Response) => {
        this.host = data.json().host;
        this.port = data.json().port;

    });  
}

由于数据是异步的,我无法通过以下方法访问它们:

interact(data:Request): Promise<Response>{       
    return this.http.post("http://" + this.host + ":" + this.port, data)
        .toPromise()
        .then(data => data.json() as Response)
        .catch(this.handleError);
}

所以,当我从另一个服务调用 interact() 时,hostport 是未定义的。 是否可以等待设置此变量,然后执行post 请求?我不想在interact() 中调用get,因为可以有很多函数使用这些变量。

如果有任何建议,我将不胜感激。

【问题讨论】:

  • 我使用了一种方法来完成此任务,即不要订阅服务文件中的 http,取而代之的是,您可以在需要数据的地方订阅它。
  • 我很好奇这种模式是否有帮助? stackoverflow.com/a/44051264/4614870
  • @Brian,获取该 Observable 的 null

标签: javascript jquery angular angular2-services


【解决方案1】:

我认为一种方式是这样的:您可以创建一个主题并将其用作信使...:

@Injectable()
export class interaction{
private host: string="";
private port: string = "";
messenger$: Subject<boolean> = new Subject();
constructor(private http: Http) {

    this.http.get("/interaction.json").subscribe((data: Response) => {
        this.host = data.json().host;
        this.port = data.json().port;
        this.messenger$.next(true)
    });  
}

在交互内部(如果是另一个类,首先注入交互服务,然后)这样做:

interact(data:Request): Observable<any>{ 
    return this.messenger$ //or this.interaction.messenger$
        .switchMap(
            (bool: boolean)=>{
                if(bool){
                    return this.http.post("http://" + this.host + ":" + this.port, data)

                }
                else{
                    // return anything that would help your situation like: Observable.of(null)
                }
            }
        )
}

然后在结果上调用toPromise 或...

【讨论】:

  • 无法访问this.messenger$ nor this.interaction.messenger$,你知道为什么吗?
  • interact 方法放在哪里?在interaction 类之外?
  • 在类内
  • this.messenger$ 应该可以工作。确切的错误是什么?
  • 只能在 interact() 方法中访问。错误是:The 'this' context of type 'Subject&lt;boolean&gt;' is not assignable to method's 'this' of type 'Observable&lt;boolean&gt;'. Types of property 'lift' are incompatible.
猜你喜欢
  • 2017-06-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-04
  • 2016-11-02
  • 2012-05-25
  • 1970-01-01
  • 2017-04-05
  • 2018-01-27
相关资源
最近更新 更多