我有一个angular2应用程序,我添加登录到它。因此,登录页面将首先出现,如果登录成功,则可以访问应用程序的其余部分。angular2登录和后续路由
但是我不知道我是如何处理路由。到目前为止,除了所有其他组件外,我还创建了具有component.ts,service和html的Authentication组件。
我顶层app.component.ts:
@Component({
selector: 'my-app',
templateUrl: './app/app.component.html',
styleUrls:['./app/app.component.css'],
directives:[ROUTER_DIRECTIVES, Navbar, Stepper, Cart],
providers:[CartService, ProgressService, LoginService]
})
export class AppComponent {}
路线:
export const routes: RouterConfig = [
{ path: '', component: Home },
{ path: 'login', component: LoginComponent }, <- I was just trying this
{ path: 'about', component: About },
{ path: 'hall', component: HallComponent },
{ path: 'caterer', component: CatererComponent }
];
export const APP_ROUTER_PROVIDERS = [
provideRouter(routes)
];
最上面的应用程序的HTML:
<navbar></navbar>
<router-outlet></router-outlet>
于是就登录成功我将导航到'Home'
登录服务:
@Injectable()
export class LoginService extends BaseService {
public errorMessage: string;
constructor (http: Http) {super(http);}
private _authenticationUrl = this._baseUrl + 'rest-auth/'; // URL to web api
login(username: string, password: string) {
let body = JSON.stringify({
'username' : username,
'password': password
});
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
this.http.post(this._authenticationUrl + 'login/', body, options)
.map(this.extractData)
.catch(this.handleError).subscribe(data => this.setToken(data.key),
error => this.errorMessage = <any>error);
}
setToken(key: string) {
console.log(key);
localStorage.setItem('auth_token', key);
/*do routing here*/
// this.nav.setRoot(StartPage);
}
}
Home.component.html:
<div class="mdl-grid">
<div class="mdl-cell mdl-cell--12-col">
<p>Home component</p>
...
<div>
<hall *ngIf = "makeHallsvisible" [city]="specific_city" [date]="date" (setProduct)="setProduct($event)"></hall>
<caterer *ngIf = "makeCaterersvisible" [city]="specific_city" (setProduct)="setProduct($event)"></caterer>
https://angular.io/docs/ts/latest/guide/router.html#!#guards –
角度路由为此增加了警卫。退房@GünterZöchbauer的链接 –
当然!非常感谢。 – Nitish