dashboard.component.ts文件
import { Injectable } from '@angular/core';
import {Router} from '@angular/router';
import {Http, Headers, Response,RequestOptions} from '@angular/http';
import { Component } from '@angular/core';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import {Observable} from 'rxjs/Rx';
import { Login } from './login';
@Component({
moduleId: module.id,
selector: 'dashboard',
templateUrl: './dashboard.html',
template : '<router-outlet></router-outlet>'
})
export class DashboardComponent {
}
我已定义路线的module.ts文件
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import {Router} from '@angular/router';
import { HttpModule, JsonpModule } from '@angular/http';
import { RouterModule, Routes } from '@angular/router';
import { AppComponent } from './app.component';
import { LoginFormComponent } from './login-form.component';
import { DashboardComponent } from './dashboard.component';
const appRoutes: Routes = [
{ path: 'dashboard', component: DashboardComponent },
];
@NgModule({
imports: [
BrowserModule,
FormsModule,
HttpModule,
JsonpModule,
RouterModule.forRoot(appRoutes)
],
declarations: [
AppComponent,
LoginFormComponent,
DashboardComponent
],
bootstrap: [ AppComponent ]
})
export class AppModule { }
我是angular2的新手,我正在设计一个登录页面。现在,我想在单击提交按钮后对用户进行适当的身份验证后打开一个新页面。请建议我如何做到这一点的一些替代方案?以下是login.component.ts文件。谢谢 更新的代码
import { Injectable } from '@angular/core';
import {Router} from '@angular/router';
import {Http, Headers, Response,RequestOptions} from '@angular/http';
import { Component } from '@angular/core';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import {Observable} from 'rxjs/Rx';
import { Login } from './login';
@Component({
moduleId: module.id,
selector: 'login-form',
templateUrl: './login-form.component.html',
})
export class LoginFormComponent {
constructor (private http: Http,private _router:Router) {}
data = {
'email': '',
'password': ''
};
formSubmit (body: Object): Observable<Login[]>{
let bodyString = JSON.stringify(body);
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' }); // ... Set content type to JSON
let options = new RequestOptions({ headers: headers });
var params = "username=" + this.data.email + "&password=" + this.data.password;
var resp = this.http.post("http://localhost:8000/login", params, options) // ...using post request
.subscribe((res:Response) => {
if(res.json().status_code == 200)
{
this._router.navigate(["../dashboard"]);
console.log("success");
}
} );
return;
}
}
答案 0 :(得分:2)
使用
constructor (private http: Http,private _router:Router) {}
if(res.json().status_code == 200)
{
this._router.navigate(["../Dashboard"]);
}
这会将用户重定向到路线中定义的仪表板。
如果您想了解更多关于:Router
的信息内部模块:
const appRoutes: Routes = [
{ path: 'dashbaord', component: DashboardComponent }
];
@NgModule({
imports: [
BrowserModule,
FormsModule,
RouterModule.forRoot(appRoutes)
],
.......
})