【问题标题】:Angular `subscribe` not setting the value when call another methodAngular`subscribe`在调用另一个方法时没有设置值
【发布时间】:2018-10-10 05:27:19
【问题描述】:

我有一个 Observable 来自我订阅数据,如果我没有设置 setTimeout 我无法获得对象的childnode。目前我设置了超时。但正在寻找正确的角度方法。

这是我的代码:

ngOnInit() {
        this.store.appData.subscribe(value => {
            this.appData = value;
            setTimeout(() => this.setLocales(), 1000); //requires this
        } );
    }


    setLocales(){
        console.log( this.appData.hdr.country );
    }

我得到的错误:

ERROR TypeError: Cannot read property 'country' of undefined
    at HeaderComponent.setLocales (header.component.ts:32)
    at SafeSubscriber.eval [as _next] (header.component.ts:26)
    at SafeSubscriber.__tryOrSetError (Subscriber.js:252)
    at SafeSubscriber.next (Subscriber.js:192)
    at Subscriber._next (Subscriber.js:131)
    at Subscriber.next (Subscriber.js:95)
    at BehaviorSubject._subscribe (BehaviorSubject.js:30)
    at BehaviorSubject.Observable._trySubscribe (Observable.js:172)
    at BehaviorSubject.Subject._trySubscribe (Subject.js:98)
    at BehaviorSubject.Observable.subscribe (Observable.js:160)

ERROR CONTEXT DebugContext_ {view: {…}, nodeIndex: 17, nodeDef: {…}, elDef: {…}, elView: {…}}

【问题讨论】:

  • 不给超时会有什么错误?
  • 由于child 元素未从undefined 获取而出现错误
  • @FranklinPious - 从控制台添加了所有错误

标签: angular angular5 angular-observable


【解决方案1】:

为 value 提供一个 any 类型或提供相应的 interface 并在 subscribe 函数中提供检查。

ngOnInit() {
    this.store.appData.subscribe((value: any) => {
        if(value && value.hdr) {
        this.appData = value;
        this.setLocales(); 
      }
    } );
}

希望这行得通。

【讨论】:

  • 不走运。得到相同的错误/问题。我想这是延迟的问题!
  • console.log(value) 里面订阅的值是多少?它会打印两次吗?
  • 从服务中获得我需要的确切价值
  • 使用 Observables 时通常不会发生延迟。可能是其他问题。是否可以提供plunker?
  • 是的,打印 2 次。首先是空的,其次是加载数据。我正在处理一个大项目,我不能把它放进去。你有Skype吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-17
  • 2017-01-16
  • 2016-08-31
相关资源
最近更新 更多