Variable This.router undefined within a function

1

I'm working on Angular with TypeScript. insert a table with DataTables and in the button configuration I have an indefined error, you can support me to tell me how to use the This object within a function. I show my example code:

import { Component, OnInit } from '@angular/core';
import { MSOService } from '../../services/mso.services';
import { Subject } from 'rxjs/Subject';
import { ActivatedRoute, Router } from '@angular/router';

@Component({
  selector: 'app-objetos',
  templateUrl: './objetos.component.html',
  styleUrls: []
})
export class ObjetosComponent implements OnInit {

    objetos:any [] = [];
    titles:any [] = [];
    url_activo:object ;
    dtOptions: any = {};
    dtTrigger: Subject<any> = new Subject();

    constructor(public activatedRoute: ActivatedRoute,
                public _msoService: MSOService,
                public router: Router) {
        this.activatedRoute.params
            .subscribe( params => {
                this.url_activo = params;
            });                  
    }

    ngOnInit(): void {
        this.dtOptions = {
            pagingType: 'full_numbers',
            pageLength: 10,
            dom: 'Bfrtip',
            scrollx: true,
            scrolly: true,
            buttons: [
                {
                    extend: 'colvis',
                    collectionLayout: 'fixed two-column',
                    postfixButtons: [ 'colvisRestore' ]
                },
                'copy',
                'print',
                'excel',
                'csv',
                'pdf',
                {
                    text: 'Add ',
                    key: '1',
                    action: function (e, dt, node, config) {
                        //aqui es donde esta el error, this router no definida.
                        this.router.navigate(['nuevo']);
                    }
                }
            ],

            columnDefs: [
                {
                    targets: [0,1],
                    visible: false
                }
            ]
        };

        this.activatedRoute.params
            .subscribe( params => {
                this._msoService.getObjetos( params['APPNAME'], params['MODELNAME'])
                    .subscribe(objetos => {
                        this.objetos = objetos;
                        this.titles = Object.keys(objetos[0]);
                        this.dtTrigger.next(objetos);
                    });
            });
        }
    }
    
asked by Raul Cervantes 14.05.2018 в 13:56
source

1 answer

0

You're losing the context. You have 3 ways to fix it: use bind , save the context in a variable external to the function or declare the function as an function arrow . I advise you to use the third option for simplicity:

...
{
  text: 'Add ',
  key: '1',
  action: (e, dt, node, config) => {
    this.router.navigate(['nuevo']);
  }
}
...
    
answered by 14.05.2018 / 15:22
source