【问题标题】:Angular 5 component global variable is undefined?Angular 5 组件全局变量未定义?
【发布时间】:2018-03-09 10:33:00
【问题描述】:

我的问题是当调用 ngOnIt 、 AfterViewInit 方法时,全局变量是 undefined。 我正在从资产文件夹中的 json 文件中获取数据。我已经成功地将数据传递给gotodef() 函数,并带有一个参数。从那个gotodef() 函数我返回变量。 我需要的是我想返回 gotodef() 函数中满足 json 文件条件的数组(我的意思是来自订阅方法)。

以下是我的代码,

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%'}
            ];


    }

所以,从这次检查中我发现它第一次是未定义的,然后是设置值。

EDIT-2 :-

谢谢@ChrisG。 我的问题令人困惑,所以我试图解释一下。

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

Jqwidget 的代码和gotodef() 函数属于同一类。 所以,我可以像这样从函数的参数-1 中获取 json 文件的数据,gotodef(argument-1) 在订阅者方法中,我可以将它传递给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 : any。我得到 Column_data_which_I_havetoreturn 但这是第一次未定义。

【问题讨论】:

  • this.column_data 的设置如何?
  • 我猜你需要this.column_data = this.gotodef(default_columns); 但是你的代码不完整,我很难理解这里的实际问题。如果您遇到错误,请逐字显示错误并提及导致错误的行。
  • @CruelEngine。实际上问题是我无法正确设置它的值,因为我从gotodef() 函数返回值,我必须在columns: any[] = this.gotodef(this.column_data); 这一行中设置这个返回值。
  • @WebRence 但是columns: 在哪里?我在任何一个 sn-ps 中都没有看到它。您是否将其与 column_data 混淆了?
  • @ChrisG。谢谢你的回复,但是我必须把这段代码放在 subscibe 方法中吗?

标签: javascript angular angular5


【解决方案1】:

你可以试试这个解决方案(我改了几个名字):

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 调用后更新它。

【讨论】:

  • 谢谢你,克里斯。从字面上看,你已经花了很多时间来回答这个问题。这意味着很多。
【解决方案2】:

你可以试试这个方法

this.gotodef(this.column_data);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-08
    • 2018-09-17
    • 1970-01-01
    • 1970-01-01
    • 2018-11-16
    相关资源
    最近更新 更多