原始类型按引用传递的解决方法

问题描述 投票:0回答:1

我遇到了问题,而且不是 async/rxjs 开发专家。

让我解释一下我的问题:

我有一个角度服务

TimeoutService
,它只包含一个
processTimeout()
方法:


  processTimeout(timeout: NodeJS.Timeout, stillLoading: boolean): void {
    if (timeout !== undefined) {
      clearTimeout(timeout);
    }

    timeout = setTimeout(() => {
        if (stillLoading) this.dialog.open(LoadingDialogComponent);
    }, this.TIMEOUT_DURATION_MS);
  }

processTimeout()
执行以下操作:

  • 采用

    NodeJS.Timeout
    作为参数,以及
    stillLoading
    boolean

  • 首先检查超时是否已经开启,如果是则清除。

  • 然后我设置超时,如果在超时回调时,

    stillLoading
    值是
    true
    (这总是因为当我将它作为参数从
    processTimeout
    传递给
    componentA
    方法时,值是
    true
    ) ,我打开一个对话框,说该请求需要很长时间。

问题是,传递给方法的

stillLoading
布尔值是我的标准角度组件的一个属性(例如,让我们称其为
ComponentA
,它具有
boolean
loadingA
属性),并且我已经知道 js/ts 有原始类型的值传递:

当我调用我的 api 服务时,它设置为 true;当加载完成时(当订阅我的 api 请求已完成时),它设置为 false。

但是在我从服务中调用

loadingA
方法后,将
processTimeout()
的值设置为 false。

  1. 所以我的问题是,最好的方法/最佳实践是什么,以便
    processTimeout()
    中使用的布尔值保留引用或指针(对我来说也是如此,但我真的不知道 Js/Ts 在幕后如何工作,而是一个变量应该有一个内部存储器/ DOM Hex 地址)或者甚至是可观察的或者其他东西,这样
    stillLoading
    processTimeout()
    的值与我的
    loadingA
    的属性
    componentA
    保持相同? (属性
    loadingA
    作为
    stillLoading
    参数传递,也是
    boolean
    中的原始
    componentA
    类型)。

由于超时的性质使得其中的代码在超时后执行,我需要当时的布尔值(来自

componentA
),而不是方法中按值传递时的值.
我愿意倾听每一个可能的解决方案,如果可能的话,尊重 ts 和角度最佳实践。

  1. 在编写问题时,我还认为我也需要针对超时对象使用相同的解决方案(但由于它是一个对象,因此它应该已经通过引用传递了,对吧?)

谢谢。

尝试过:说实话,没有太多,因为在这个问题上浪费时间之前,我更喜欢一些建议,有一个想法在我的

componentA
loadingA
属性上传递一个新实例化的可观察指向,但我根本不确定我对可观察量在此类情况下的工作方式的理解。

预期:

stillLoading
中的
processTimeout
方法参数与我的
componentA
loadingA
布尔属性相同的变量(相同的内存地址),或者我可以用来满足我的需求的工具的任何解决方案/线索。

angular typescript observable pass-by-reference pass-by-value
1个回答
0
投票

正如你所说,你可以通过参考并确保服务具有最新的价值!

在你的组件中,你可以这样称呼它

export class ParentA {
    loadingWrapper = {
        loading: false,
    }

    constructor(private timeoutService: TimeoutService) {}

    ngOnInit() {
        this.timeoutService(5000, this.loadingWrapper);
        this.loadingWrapper.loading = true;
    }

}

在您的服务中您可以将其更改为

  processTimeout(timeout: NodeJS.Timeout, stillLoadingWrapper: {loading: boolean}): void {
    if (timeout !== undefined) {
      clearTimeout(timeout);
    }

    timeout = setTimeout(() => {
        if (stillLoadingWrapper.loading) this.dialog.open(LoadingDialogComponent);
    }, this.TIMEOUT_DURATION_MS);
  }
© www.soinside.com 2019 - 2024. All rights reserved.