【问题标题】:Return Rx value not available when passed into Angular ForEach传递给 Angular ForEach 时返回 Rx 值不可用
【发布时间】:2018-04-09 16:10:59
【问题描述】:

我订阅了 Rx 返回并将其传递给 Angular.ForEach 循环但它的值未定义。但是,我设法在 console.log 打印上得到结果。

下面是调用打字稿代码

this.wordPressBlogPostRepository.getPortfolios().subscribe(
    (result) => {
        this.stopLoading();
        this.viewmodels = result;
        console.log(this.viewmodels);
        angular.forEach(this.viewmodels, function (value, key) {
            this.viewmodels[key].title.rendered = value.title.rendered.replace("Softinn Portfolios: ", "");
        });
    },
    (error) => {
        swal({
            title: 'Error',
            text: error,
            type: "error"
        });
        this.stopLoading();
    }
);

以下是错误信息:

未捕获的类型错误:无法读取未定义的属性“viewmodels” 在 AngularControllers?v=rVYJl6CURXT7t6FM4ZFRtRuO0C-mN9uPa6W1ArXQ9301:1 在 Object.t [as forEach]

如果我这样做,它会起作用

this.wordPressBlogPostRepository.getPortfolios().subscribe(
    (result) => {
        this.stopLoading();
        this.viewmodels = result;
        console.log(this.viewmodels);
        for (var blogCounter = 0; blogCounter < this.viewmodels.length; blogCounter++) {
            this.viewmodels[blogCounter].title.rendered = this.viewmodels[blogCounter].title.rendered.replace("Portfolios: ", "");
        }
    },
    (error) => {
        swal({
            title: 'Error',
            text: error,
            type: "error"
        });
        this.stopLoading();
    }
);

我错过了什么?我应该使用(完成)而不是(结果)吗?

【问题讨论】:

    标签: angularjs typescript rxjs


    【解决方案1】:

    这可能是因为 this 在您的 forEach 函数中的上下文。

    你可以试试:

    angular.forEach(this.viewmodels, (value, key) => {
                this.viewmodels[key].title.rendered = value.title.rendered.replace("Softinn Portfolios: ", "");
            });
    

    由于胖箭头函数维护this的上下文

    【讨论】:

      猜你喜欢
      • 2010-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-12
      • 2013-10-19
      • 1970-01-01
      • 1970-01-01
      • 2015-01-17
      相关资源
      最近更新 更多