0

我有一个 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: {…}}
4

1 回答 1

1

为 value 提供类型any或提供相应的接口并在 subscribe 函数内提供检查。

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

希望这有效。

于 2018-04-30T09:16:10.547 回答