Search code examples
angularangular2-meteor

How to access Angular 2 router in Meter.call() method


I am designing a simple login screen using Angular2-Meteor, I want to redirect user to /dashboard once login API call is successful.

import {Component} from '@angular/core';
import {MeteorComponent} from 'angular2-meteor';
import {LocalStorageService} from '../services/localstorage.service'
import {Router} from '@angular/router-deprecated';
import {LoggerService} from "../services/loggerService";

'use strict';
@Component({
    selector: 'login',
    templateUrl: 'client/login/login.html',
    bindings: [LoggerService]
})

export class LoginComponent extends MeteorComponent {

public loginData = {
    username: '',
    password: ''
};

constructor(private _logger:LoggerService, public router:Router) {
    super();
}

login() {
    this._logger.log('Login attempted ', this.loginData);

    this.call('authenticateUser', this.loginData.username, this.loginData.password , function (err, data) {
        if (err) {
            this._logger.error(err);

        } else {

            console.info(JSON.parse(data));
            console.log(this.router);
            this.router.navigate(['Dashboard'])
        }
      });
    }
}

I am not able to access the router in Meteor.call(). I have tried passing this reference to Meteor.call by doing self = this, but it takes selfas Window.

Can someone please help with this? Thank you in advance.


Solution

  • You have to use the arrow function to have the same this context within a class.

    Change your anonymous callback function like this:

    this.call('authenticateUser', 
              this.loginData.username, 
              this.loginData.password, 
              (err, data) => {
       //...
    });
    

    hint

    Try to look into promises or observables instead of using a callback function