我有一個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