我有两个组件。logincomponent和landingcomponent。我必须在验证用户名和密码后从登录页路由到landingpage。但是我不能访问服务内部的路由器,因为它是全局/页面变量。它显示错误“typeerror:无法读取属性‘router’”。

import {Component} from 'angular2/core';
import { RouteConfig, ROUTER_DIRECTIVES, ROUTER_PROVIDERS, Router } from 'angular2/router';
import {LoginService} from './login.service';
import {NgForm} from 'angular2/common';

@Component({
    selector: 'login',
    templateUrl: './app/app-components/login/login.html',
    styleUrls:['./app/app-components/login/login.css'],
    directives: [ROUTER_DIRECTIVES],
    providers:[LoginService]
})
export class LoginComponent {

  //DECLARATIONS
  login={username:"",password:""} ;
  active = true;
  submitted = false;
  router:Router;

  constructor(private _loginService: LoginService,private _router: Router) {
    this.router = _router;
   }

  onAuthenticate() {
      this.submitted = true;
      this._loginService.Login().then( function (loginValues) {
          if(loginValues.username=="sampleuser" && loginValues.password=="a"){
            this.router.navigate(['LandingPage']);
          }
          else{
           alert("Invalid Username or Password!!");
          }
      });
   }
}

服务函数
import {Injectable} from 'angular2/core';

@Injectable()
export class LoginService {
    Login(){
    return Promise.resolve(login);
    }
}

var login={
    username:"sampleuser",
    password:"a"
}

最佳答案

您应该在logincomponent中使用这样的arrow-functions

this._loginService.Login().then( (loginValues) => {
    if(loginValues.username=="sampleuser" && loginValues.password=="a"){
        this.router.navigate(['LandingPage']);
    }
    else{
        alert("Invalid Username or Password!!");
    }
});

这不会改变函数内部的this。否则,这不会指向logincomponent的实例,并且找不到路由器。

10-06 00:10