私は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>
私はに移動します「ホーム」
ログインサービス:
@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