我有兩個組件.LoginComponent和LandingComponent.I必須在驗證用戶名和密碼後從登錄頁面轉到登錄頁面。但是我無法訪問全局/頁面變量的服務中的路由器。它顯示一個錯誤「TypeError:無法讀取屬性'路由器'」。如何訪問服務中的全局變量?
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!!");
}
});
}
}
login服務
import {Injectable} from 'angular2/core';
@Injectable()
export class LoginService {
Login(){
return Promise.resolve(login);
}
}
var login={
username:"sampleuser",
password:"a"
}
你的路由配置在哪裏?也許你錯過了添加它,因爲裝飾器是導入你的LoginComponent – Dinistro