RxJS subscription()函数内部的组件变量未定义 [英] Component variables inside a RxJS subscribe() function are undefined

查看:93
本文介绍了RxJS subscription()函数内部的组件变量未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

订阅中的变量是未定义的,但是当我在到达服务订阅之前放置断点时,我已定义了变量.

Variables inside subscribe are undefined but when I put breakpoint before hitting service subscribe I have the variable defined.

服务中:

getCashierRiskProfiles(): Observable<ICashierRiskProfile[]> {
  return this.http.get(this._baseUrl + "src/HTTPJson/cashierriskprofile.json")
    .map((res: Response) => res.json())
    .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
}

在组件中:

import { Component, OnInit } from "@angular/core";
import { Observable } from 'rxjs/Observable';

import { CashierRiskProfileService } from "./cashierriskprofile.service";
import { ICashierRiskProfile } from "../shared/interfaces";

@Component({
  selector: "cashierriskprofile",
  templateUrl: "../src/app/cashierriskprofile/cashierriskprofile.component.html"
})
export class CashierRiskProfileComponent implements OnInit {
  filterText: string;
  cashierRiskProfiles: ICashierRiskProfile[];

  constructor(
    private sorter: Sorter,
    private service: CashierRiskProfileService
  ) { }

  ngOnInit() {
    this.filterText = "Filter Exceptions:";
    //// Observable technique
    this.service.getCashierRiskProfiles()
      .subscribe(
        (riskProfiles) => {
          this.cashierRiskProfiles = riskProfiles;
          this.filterText = "Inside Subscribe:";
        },
        err => {
          // Log errors if any
          console.log(err);
        }
      );
  }
}

在上述ngonInit()服务调用内的组件代码中,未定义subscribe中的this.cashierRiskProfiles,但是在我在服务调用之前放置断点之后,我就有了可用的变量并已定义.

In above component code inside ngonInit() service call, this.cashierRiskProfiles inside the subscribe is undefined, but after I put breakpoint before the service callI have that variable available and defined.

我已经看到很多人都对组件变量有这个问题,而this.variablename在内部未定义.当您注意到this.filterText时,可以在dataservice调用之外获取分配给它的值,但是当我在subscribe中放置断点时,this.filterText是未定义的,并且我不知道该如何丢失它.

I have seen lot of people having this issue with component variables with this.variablename getting undefined inside subscribe. When you notice this.filterText I can get the values assigned to it outside dataservice call, but when I put breakpoint inside subscribe, this.filterText is undefined and I don't know how I am losing it.

这是怎么回事?

推荐答案

我想是因为在运行时,内部订阅是SafeSubscribe,而不是您的组件.

I guess it's because during runtime this inside subscribe is SafeSubscribe, not your component.

使用闭包调用组件方法,如下所示:

use closure to call component method, like this:

populateCashierRiskProfiles() {
    const that = this;
    //// Observable technique
    this.service.getCashierRiskProfiles()
        .subscribe((riskProfiles) => {
            that.cashierRiskProfiles = riskProfiles
        });
}

这篇关于RxJS subscription()函数内部的组件变量未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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