繁体   English   中英

Angular 5组件全局变量未定义?

[英]Angular 5 component global variable is undefined?

我的问题是,在ngOnItAfterViewInit方法时,全局变量undefined 我正在从资产文件夹中的json文件中获取数据。 我已成功通过一个参数将数据传递给gotodef()函数。 从该gotodef()函数中,我返回了变量。 我需要的是要返回满足json文件中条件的gotodef()函数中的数组(我的意思是来自subscription方法)。

以下是我的代码,

export class DashboardComponent implements AfterViewInit {

 column_data : any;

 constructor(private router:Router,private http:Http) {
            this.http.get('http://localhost:4200/assets/world_bank.json')
             .subscribe(data => {
                      data = (<any>data)._body;
                      let obj: MyObj = JSON.parse(data);
                      let outage_columns = obj.Outage.Columns;
                      let default_columns = obj.Default.Columns; // default_column's value is 2 in this case.
                      if(outage_columns == '')
                      {
                          let column_data = default_columns;
                          this.gotodef(column_data);
                      }

              });
    }
}

Gotodef功能:-

gotodef(column_data:any)
{

    if(column_data === '2')
    {
        console.log('in if statement');

        let columndata_1 = [
                { text: 'Product Name 1',  datafield: 'ProductName', width: '20%' , hidden:true },
                { text: 'Quantity per Unit',  datafield: 'QuantityPerUnit', cellsalign: 'right', align: 'right' , width: '20%'},
                { text: 'Unit Price',  datafield: 'UnitPrice', align: 'right', cellsalign: 'right', cellsformat: 'c2', width: '20%' },
                { text: 'Units In Stock', datafield: 'UnitsInStock', cellsalign: 'right', cellsrenderer: this.cellsrenderer, width: '20%' },
                { text: 'Discontinued', columntype: 'checkbox', datafield: 'Discontinued', align: 'center' , width: '20%'}
            ];
        return columndata_1;
    }
}

现在,这是jqwidgets组件的行, 我想在this.column_data中使用函数的返回值,但是我可以返回它的值,但是第一次它是未定义的。

columns: any[] = this.gotodef(this.column_data);

所以,我很困惑如何完成这项任务。 如何声明适当的变量来执行此任务。

编辑:-

完整代码(带有Jqwidgets代码)

@ViewChild('myGrid') myGrid: jqxGridComponent;

Rowclick(event: any): void {
    var args = event.args;
    var selectedRowIndex = args.rowindex;
    // alert(selectedRowIndex);
    $('#right_panel').css('display','block');
    $('body').removeClass('aside-menu-hidden');
}
source: any =
{
    datatype: 'xml',
    datafields: [
        { name: 'ProductName', type: 'string'  },
        { name: 'QuantityPerUnit', type: 'int' },
        { name: 'UnitPrice', type: 'float' },
        { name: 'UnitsInStock', type: 'float' },
        { name: 'Discontinued', type: 'bool' }
    ],
    root: 'Products',
    record: 'Product',
    id: 'ProductID',
    url: '../../assets/product.xml'
};

dataAdapter: any = new jqx.dataAdapter(this.source);

cellsrenderer = (row: number, columnfield: string, value: string | number, defaulthtml: string, columnproperties: any, rowdata: any): string => {
    if (value < 20) {
        return `<span style='margin: 4px; float:${columnproperties.cellsalign}; color: #ff0000;'>${value}</span>`;
    }
    else {
        return `<span style='margin: 4px; float:${columnproperties.cellsalign}; color: #008000;'>${value}</span>`;
    }
};

gotodef(column_data:any)
{
    console.log(column_data);
    if(column_data === '1')
    {
        console.log('in if');
        let columndata_1 = [
                { text: 'Product Name 1',  datafield: 'ProductName', width: '20%' },
                { text: 'Quantity per Unit',  datafield: 'QuantityPerUnit', cellsalign: 'right', align: 'right' , width: '20%'},
                { text: 'Unit Price',  datafield: 'UnitPrice', align: 'right', cellsalign: 'right', cellsformat: 'c2', width: '20%' },
                { text: 'Units In Stock', datafield: 'UnitsInStock', cellsalign: 'right', cellsrenderer: this.cellsrenderer, width: '20%' },
                { text: 'Discontinued', columntype: 'checkbox', datafield: 'Discontinued', align: 'center' , width: '20%'}
            ];
        return columndata_1;
    }
    if(column_data === '2')
    {
        console.log('in second if');
        let columndata_1 = [
                { text: 'Product Name 1',  datafield: 'ProductName', width: '20%' , hidden:true },
                { text: 'Quantity per Unit',  datafield: 'QuantityPerUnit', cellsalign: 'right', align: 'right' , width: '20%'},
                { text: 'Unit Price',  datafield: 'UnitPrice', align: 'right', cellsalign: 'right', cellsformat: 'c2', width: '20%' },
                { text: 'Units In Stock', datafield: 'UnitsInStock', cellsalign: 'right', cellsrenderer: this.cellsrenderer, width: '20%' },
                { text: 'Discontinued', columntype: 'checkbox', datafield: 'Discontinued', align: 'center' , width: '20%'}
            ];


    }
}

columns: any[] = this.gotodef(this.column_data);

columngroups: any[] =
[
    { text: 'Product Details', align: 'center', name: 'ProductDetails' }
];

如果我把这样的条件奏效,

if(column_data === '2' || typeof column_data === 'undefined')
    {
        console.log('in second if');
        let columndata_1 = [
                { text: 'Product Name 1',  datafield: 'ProductName', width: '20%' , hidden:true },
                { text: 'Quantity per Unit',  datafield: 'QuantityPerUnit', cellsalign: 'right', align: 'right' , width: '20%'},
                { text: 'Unit Price',  datafield: 'UnitPrice', align: 'right', cellsalign: 'right', cellsformat: 'c2', width: '20%' },
                { text: 'Units In Stock', datafield: 'UnitsInStock', cellsalign: 'right', cellsrenderer: this.cellsrenderer, width: '20%' },
                { text: 'Discontinued', columntype: 'checkbox', datafield: 'Discontinued', align: 'center' , width: '20%'}
            ];


    }

因此,通过此检查,我发现它是第一次未定义,然后才是设置值。

编辑2 :-

谢谢@ChrisG。 我的问题令人困惑,因此我尝试对其进行解释。

我需要的是要返回满足json文件中条件的gotodef()函数中的数组(我的意思是来自subscription方法)。

Jqwidget的代码和gotodef()函数在同一类中。 因此,我可以像这样从订户方法中的函数的参数1 gotodef(argument-1)获取json文件的数据,并将其传递给gotodef()

因此,我可以从函数中获取column_data ,而column_data的值为'2',可能为1,2或3等。

现在,如果column_data具有2值,那么我必须更改数组。 请参见下面的代码。

if(column_data === '2')
    {
        console.log('in second if');
        let Column_data_which_I_havetoreturn = [
                { text: 'Product Name 1',  datafield: 'ProductName', width: '20%' , hidden:true },
                { text: 'Quantity per Unit',  datafield: 'QuantityPerUnit', cellsalign: 'right', align: 'right' , width: '20%'},
                { text: 'Unit Price',  datafield: 'UnitPrice', align: 'right', cellsalign: 'right', cellsformat: 'c2', width: '20%' },
                { text: 'Units In Stock', datafield: 'UnitsInStock', cellsalign: 'right', cellsrenderer: this.cellsrenderer, width: '20%' },
                { text: 'Discontinued', columntype: 'checkbox', datafield: 'Discontinued', align: 'center' , width: '20%'}
            ];

     return Column_data_which_I_havetoreturn;
    }

现在我必须将返回的数据用于此语法,

columns: any[] = this.gotodef(Column_data_which_I_havetoreturn);

因此,为此,我在Column_data_which_I_havetoreturn Column_data_which_I_havetoreturn的类中声明了Column_data_which_I_havetoreturn变量Column_data_which_I_havetoreturn : any 我正在获取Column_data_which_I_havetoreturn,但这是第一次未定义。

您可以尝试以下解决方案(我改了几个名字):

 class DashboardComponent { columnDataIndex = 1 // initial value constructor() { this.columns = this.getColumnData(this.columnDataIndex) // initialize this.columns // ajax call here // in subscribe, do: setTimeout(() => { console.log("ajax call succeeded"); this.columnDataIndex = 2 this.columns = this.getColumnData(this.columnDataIndex) }, 500); } getColumnData(index) { var column_data = [ { text: 'Product Name 1', datafield: 'ProductName', width: '20%' }, { text: 'Quantity per Unit', datafield: 'QuantityPerUnit', cellsalign: 'right', align: 'right' , width: '20%'}, { text: 'Unit Price', datafield: 'UnitPrice', align: 'right', cellsalign: 'right', cellsformat: 'c2', width: '20%' }, { text: 'Units In Stock', datafield: 'UnitsInStock', cellsalign: 'right', cellsrenderer: this.cellsrenderer, width: '20%' }, { text: 'Discontinued', columntype: 'checkbox', datafield: 'Discontinued', align: 'center' , width: '20%'} ]; if (index == 2) column_data[0].hidden = "true"; return column_data; } columns : any } const DC = new DashboardComponent(); console.log("columns", DC.columns[0]); setTimeout(() => { console.log("columns", DC.columns[0]); }, 1000); 

这些字段可以说明一切,但是基本的思想是,到目前为止,AJAX调用仅更改了最终以.columns结尾的列数据的类型,因此我在构造函数中添加了初始值1 ,初始化.columns ,然后在成功(模拟)的AJAX调用后对其进行更新。

你可以这样尝试

this.gotodef(this.column_data);

暂无
暂无

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

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