简体   繁体   English

静态JSON对象上异步数据的Angular2问题

[英]Angular2 Issues with Async data on static JSON objects

I have a service set up with some static objects that I am using in my UI. 我的服务中设置了一些我在UI中使用的静态对象。

fetchRulesVariables() fetchRulesVariables()

fetchRuleVariables() {

    let variables = [

        {
            name: 'Credit Funding Type',
            id: 1,
            multiple: false,
            hasOperators: true,
            availableOperators: this.fetchOperators('inResults'),
            inputType: 'single',
            placeholder: 'Select a funding type',
            availableValues: this.fetchFundingInstraments()
        }, {
            name: 'Device Trust Score',
            id: 2,
            multiple: false,
            hasOperators: true,
            availableOperators: this.fetchOperators('gtltResults'),
            inputType: 'text',
            placeholder: 'Enter a value between 0 - 100',
            availableValues: ''
        }
    ]
 return variables;
}

This object runs another function which adds another array of data to it such as availableOperators and availableValues . 该对象运行另一个函数,该函数向其中添加另一个数据数组,例如availableOperatorsavailableValues Those too are just static json objects. 这些也只是静态json对象。

In my component, I have a function that is fetching this data by ID using lodash . 在我的组件中,我有一个函数,使用lodash通过ID提取此数据。

fetchVariableData(id, type) {

    let data = [];

    switch (type) {
        case 'operators':
            data = _.find(this.variables, {id}).availableOperators;
            break;
    }

    return data;

}

In my component HTML, I am running an ngFor using my function to fetch the results. 在我的组件HTML中,我正在运行ngFor使用我的函数来获取结果。

<li *ngFor="let x of fetchVariableData(1, 'operators')"></li>

The issue here is that I am running into some async issues I believe. 这里的问题是我遇到了一些我相信的异步问题。 When I run this, I get an error that availableOperators is undefined. 当我运行此命令时,出现一个错误,提示availableOperators未定义。 If I hardcode the operators into my fetchVariableData() function however, it works fine. 但是,如果我将运算符硬编码到fetchVariableData()函数中,则可以正常工作。

How can I handle this async issue where it appears that it is trying to use the availableOperators when it isn't ready? 在未准备好尝试使用availableOperators情况下,如何处理该异步问题?

This is all static JSON , no HTTP calls. 这都是静态JSON ,没有HTTP调用。

Edit1 EDIT1

Component Code: 组件代码:

export class AddRuleComponent implements OnInit {
    variables: any;

    ngOnInit() {
        this.loadVars();
        this.renderAddRuleForm();
    }


    loadVars() {
        this.outcomes = this._mserv.fetchOutcomeTypes();
        this.variables = this._mserv.fetchRuleVariables();
    }

    fetchVariableData(id, type) {

        let data: any;

        switch (type) {
            case 'operators':
                data = _.find(this.variables, {
                    id
                }).availableOperators;
                break;
        }
        return data;
    }

}

Service Code: 服务代码:

fetchRuleVariables() {

    let variables = [

        {
            name: 'Credit Funding Type',
            id: 1,
            multiple: false,
            hasOperators: true,
            availableOperators: this.fetchOperators('inResults'),
            inputType: 'single',
            placeholder: 'Select a funding type',
            availableValues: this.fetchFundingInstraments()
        }, {
            name: 'Device Trust Score',
            id: 2,
            multiple: false,
            hasOperators: true,
            availableOperators: this.fetchOperators('gtltResults'),
            inputType: 'text',
            placeholder: 'Enter a value between 0 - 100',
            availableValues: ''
        }
    ]
 return variables;
}

fetchOperators(type) {

    let operators = [];

    // Based on the set of operators we want
    switch (type) {

        // In Results
        case 'inResults':

            operators.push({
                name: 'In List',
                id: 1,
            }, {
                name: 'Not In List',
                id: 2,
            });

            break;

            // Greater than & Less than
        case 'gtltResults':

            operators.push({
                name: 'Greater Than <',
                id: 3,
            }, {
                name: 'Less Than >',
                id: 4,
            });

            break;

            // Is / is not
        case 'isisnot':

            operators.push({
                name: 'Is',
                id: 5,
            }, {
                name: 'Is Not',
                id: 6,
            });

            break;
    }

    return operators;
}

HTML Code: HTML代码:

 <select class="form-control input-sm" formControlName="operator" [attr.id]="'operator'+i">
   <option value="">Select an Operator</option>
   <option *ngFor="let o of fetchVariableData(1, 'operators') | values" value="{{ o.id }}">{{ o.name }}</option>
 </select>

Values Pipe: 价值管道:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({ name: 'values',  pure: false })
export class ValuesPipe implements PipeTransform {
  transform(value: any, args: any[] = null): any {
    return Object.keys(value).map(key => value[key]);
  }
}

Check the lifecycle of your component; 检查组件的生命周期;

As explained here in the official guide your AddRuleComponent calls ngOnInit() to fetch and initialize the data for the component. 官方指南所述,您的AddRuleComponent调用ngOnInit()来获取和初始化组件的数据。

As stated in the docs, the order is constructor , ngOnChanges() , ngOnInit() and so on, so by the time ngOnInit() fetches the values, your component already checked if the properties has been initialized/mutated, that's why fetchVariableData() could be called with invalid params (happening from the ngOnChanges() ) resulting in the undefined error because _.find(...) is not returning the variables object as you expect. 如文档中所述,顺序是构造函数ngOnChanges()ngOnInit()等等,因此当ngOnInit()获取值时,您的组件已经检查属性是否已初始化/突变,这就是为什么fetchVariableData( )可以使用无效的参数(从ngOnChanges()发生调用,从而导致未定义的错误,因为_.find(...)并未按预期返回变量对象。

I'd try to initialize first: 我会先尝试初始化:

variables: any = [];

and then do an *ngIf="variables.length" on the container, or move the initialization to the constructor. 然后在容器上执行*ngIf="variables.length" ,或将初始化移动到构造函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM