【问题标题】:Two sequential subscriptions on two separate observables Angular 2两个单独的可观察对象Angular 2上的两个顺序订阅
【发布时间】:2017-02-01 20:49:12
【问题描述】:

我对 Angular 2 中两个单独的 observable 的两个顺序订阅有疑问。 我正在尝试:

  1. 从坐标获取位置
  2. 将此位置附加到我的 json 中
  3. 发送json到服务器

我认为我这样做的方式是错误的:

this._locationService.geocode(this.location.latitude, this.location.longitude).
        subscribe(position => {
            this.location.city = this.findAddressPart(position, "locality", "long");
            this.location.country = this.findAddressPart(position, "country", "long");
            this._locationService.updateLocation(this.location)
                .subscribe(
                    location => {
                        this.location = location;
                        this.submitted = true;
                        this.submitting = false;
                    }
                );
        });

这样我的 DOM 在我实际获取位置后仅更新 5-10 秒。

【问题讨论】:

  • 您是否尝试在角度区域中运行它?使用 this.zone.run( () => {}) 你应该只在区域内运行位置分配
  • 它是如何工作的?
  • 请参考这篇文章:joshmorony.com/…
  • 实际问题是什么?目前没有发生的事情应该是什么?
  • 谢谢@galvan!问题是我在第二个订阅中的代码在角度之外工作并且没有运行更改检测。我在 zone.run 块中运行它,它现在可以正常工作了!

标签: angular angular2-observables


【解决方案1】:

您似乎对更新解决方案需要多长时间有疑问。不幸的是,除非您重组 _locationService 使用数据的方式,否则无法解决此问题。目前您有:

  1. 获取经纬度地理编码
  2. 等待请求完成
  3. 将请求 #1 中的数据设置到位置
  4. 从位置获取更新数据
  5. 等待请求完成
  6. 设置更新位置
  7. 更新 DOM 并更新位置

有两个请求链接在一起。如果可能的话,我会将这两个函数合并到您的后端的一个调用中,以便您可以调用类似

this._locationService.geocode(this.location.latitude, this.location.longitude).
        subscribe(location => {
            this.location = location;
            this.submitted = true;
            this.submitting = false;
        });

当然,这只有在您的服务器包含为此类请求提供服务的数据时才有效。如果您的服务器还必须进行 HTTP 调用,那么将其更改为上述将是没有实际意义的。

如果上述方法不可行,您可以在第一个请求完成后更新您的 DOM。如果一切顺利,updateLocation 函数将返回与发送到服务器相同的位置,对吧?您可以使用本地可用值更新 DOM,而不是在第二个函数成功时更新 DOM,仅在出现错误时更改它们。这将使您的响应时间看起来快 50%。像这样的。

this._locationService.geocode(this.location.latitude, this.location.longitude).
        subscribe(position => {
            this.location.city = this.findAddressPart(position, "locality", "long");
            this.location.country = this.findAddressPart(position, "country", "long");
            // SET DOM HERE using this.location values
            this._locationService.updateLocation(this.location)
                .subscribe(
                    location => {
                        this.location = location;
                        // optionally SET DOM HERE again
                        this.submitted = true;
                        this.submitting = false;
                    }, 
                    error => {
                        // SET DOM HERE reflecting error
                    }
                );
        });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-19
    • 1970-01-01
    • 2020-09-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多