【问题标题】:Cannot read property 'next' of undefined无法读取未定义的属性“下一个”
【发布时间】:2017-08-16 04:35:11
【问题描述】:

我订阅了一个 observable,这样每当我的服务中的subscribeToTasks() 调用失败时,它最终会从我的组件调用我的subscriptionError() 方法中的代码,在这个例子中这只是一个简单的警报。问题是,每当此调用发生错误并调用 this.newSubscriptionFailure.next() 时,我的浏览器控制台中都会出现以下错误:

无法读取未定义的属性“下一个”

newSubscriptionFailure 在你可以清楚地看到它被定义在方法之上时,它是如何未定义的?该代码应该在 api 调用中的错误发生之前很久就被命中。我过去使用过这种方法并且它一直有效,我能想到的唯一区别是我在服务中调用.next()(与newSubscriptionFailure 定义相同的文件)而我通常调用@987654327 @ 在单独的组件文件中。我究竟做错了什么?有什么方法可以让它发挥作用,或者有更好的方法吗?

我的服务代码:

import { Observable } from 'rxjs/Observable';
import { Subject }    from 'rxjs/Subject';

public subscribeToTasks(period: string, stripeToken: string): Observable<any> {        
    let body = JSON.stringify({ period, stripeToken });
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });        
    return this.authHttp.post(this.apiTasks, body, options).map(response => {
        return response.json();
    }).catch(this.newSubscriptionError);
}


newSubscriptionFailure = new Subject();
newSubscriptionFailure$ = this.newSubscriptionFailure.asObservable();

public newSubscriptionError() {
    this.newSubscriptionFailure.next();
}

来自我的组件的代码:

ngOnInit(): void {
    this.subscriptionError();
}

subscriptionError(){
    this.subscriptionsService.newSubscriptionFailure$.subscribe(() => {
        alert('call failed');
    });
}

【问题讨论】:

    标签: angular rxjs


    【解决方案1】:

    改变

    }).catch(this.newSubscriptionError);
    

    }).catch((e)=>this.newSubscriptionError());
    

    }).catch(this.newSubscriptionError.bind(this));
    

    您的this 不是指Injectable,否则

    【讨论】:

    • this.newSubscriptionError.bind(this) 为我修复了它,谢谢!
    • 你也可以在你的构造函数中这样写:this.newSubscriptionError = this.newSubscriptionError.bind(this)
    【解决方案2】:

    以防其他人遇到与我相同的问题。我使用了一个名为 this.destroy$ 的主题,接下来我会在 OnDestroy 方法中调用它。在订阅的 observable 中使用它,例如:.takeUntil(this.destroyed$)。我忘记初始化这个destroy$ 对象。使用destroy$: Subject&lt;any&gt; = new Subject&lt;any&gt;(); 后,错误消失了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-09
      • 2021-11-13
      • 1970-01-01
      • 2020-12-17
      • 2020-04-06
      • 2020-10-30
      • 2019-10-09
      • 1970-01-01
      相关资源
      最近更新 更多