Javascript angular 2显示/隐藏路由器出口并重定向到html页面
我创建了一个简单的应用程序。我有AD windows身份验证web api,它位于不同的域上,因此我启用了cors。我创建了一个api峰值,未经授权时返回401 app.service.ts 有两件事我很挣扎Javascript angular 2显示/隐藏路由器出口并重定向到html页面,javascript,authentication,angular,typescript,Javascript,Authentication,Angular,Typescript,我创建了一个简单的应用程序。我有AD windows身份验证web api,它位于不同的域上,因此我启用了cors。我创建了一个api峰值,未经授权时返回401 app.service.ts 有两件事我很挣扎 如何隐藏路由器出口(原因是我不想显示主页/链接) 我可以使用主div上的[hidden]来隐藏它,但是如何重定向呢?因为将不可见 app.component.html authguard.ts auth.service.ts AuthenticateController.cs 我可以隐藏菜
将不可见在单击“取消”之前,它不会重定向…另一种解决方案就像我隐藏了homeComponent上的菜单一样,但有许多authService调用,这并不优雅,我猜在Angular 2 Routes中,您有“CanActivate”和“CanActivateChild”属性。 这可用于在呈现组件之前进行授权 您可以在此处找到用法: 在您的情况下,您不必卸下路由器出口 相反:
例如:
this.router.navigate(['contact'])代码>从“@angular/Router”导入路由器
谢谢,我今天将尝试这个,我不确定第3点为什么我们需要它…如何添加多条路线?应用程序路由和子路由?第3点:这是为了提供和授权保护。它是为检查身份验证而创建的类。因此,如果您需要对任意数量的路由进行身份验证,您可以将该类作为所有这些路由的CanActivate属性。这两条路由都要加载到app.component的
。domain.com将加载默认路由,domain.com/contact将加载第二条路由感谢您的建议,但我仍停留在显示菜单上,authgard等后如何显示导航栏。第一个请求不会显示任何内容。如果需要,请验证并移动到contact。如果已验证,则在底部显示导航栏和内容
authenticateUser(): Observable<any> {
return this.http.get("http://localhost:36655/", { withCredentials: true })
.map(this.extractData)
.catch(this.handleError);
}
@Component({
moduleId: module.id,
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.css']
})
export class AppComponent {
constructor(appService: AppService) {
appService.authenticateUser()
.subscribe(response => {
//do something here because its not 401
},
error => {
if (error.indexOf("401") >= 0)
console.log("Redirect to contact page")
else {
}
});
}
}
<div>
<nav class="navbar navbar-default">
<div class="container-fluid">
<a class="navbar-brand" [routerLink]="['']">Home</a>
<ul class="nav navbar-nav">
<li><a [routerLink]="['/factory']" id="factory" name="factory">Factory</a></li>
<li><a [routerLink]="['/supplier']" id="supplier" name="supplier">Supplier</a></li>
<li><a [routerLink]="['/businessarea']" id="businessArea" name="businessArea">Business Area</a></li>
</ul>
</div>
</nav>
<router-outlet></router-outlet>
</div>
@Component({
moduleId: module.id,
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.css']
})
export class AppComponent {
private isAuthenticated: boolean = false;
constructor(private authService: AuthService) {
this.authService.authenticateUser()
.subscribe(response => {
if (response.status == 200)
this.isAuthenticated = true;
},
error => {
if (error.indexOf("401") >= 0)
this.isAuthenticated = false;
});
}
}
@Injectable()
export class AuthGuard implements CanActivate {
private isActive: boolean = true;
constructor(private authService: AuthService, private router: Router) {
}
canActivate(): boolean {
this.authService.authenticateUser()
.subscribe(() => {},
error => {
if (error.indexOf("401") >= 0) {
let link = ['contactus'];
this.router.navigate(link);
this.isActive = false;
}
});
return this.isActive;
}
}
@Injectable()
export class AuthService {
constructor(private http: Http) {
}
authenticateUser(): Observable<any> {
return this.http.get("http://localhost:5002/api/v1/authenticate", { withCredentials: true })
.map(this.extractData)
.catch(this.handleError);
}
private extractData(response: Response) {
let body = response;
return body || {};
}
private handleError(error: Response) {
let errMsg: string;
if (error instanceof Response) {
errMsg = `${error.status} - ${error.statusText || ''}`;
} else {
errMsg = error.toString();
}
return Observable.throw(errMsg);
}
}
<div>
<nav class="navbar navbar-default">
<div class="container-fluid">
<a class="navbar-brand" [routerLink]="['']">Ethos</a>
<ul class="nav navbar-nav" *ngIf="isAuthenticated">
<li><a [routerLink]="['/factory']" id="factory" name="factory">Factory</a></li>
<li><a [routerLink]="['/supplier']" id="supplier" name="supplier">Supplier</a></li>
<li><a [routerLink]="['/businessarea']" id="businessArea" name="businessArea">Business Area</a></li>
</ul>
</div>
</nav>
<div>
<router-outlet></router-outlet>
</div>
</div>
const routes: Routes = [
{
path: '', component: HomeComponent, pathMatch: 'full', canActivate: [AuthGuard]
},
{ path: 'factory', component: FactoryFormComponent, canActivate: [AuthGuard]},
//...some other
{ path: 'contactus', component: ContactUsComponent }
];
public HttpResponseMessage Get()
{
return User.Identity.IsAuthenticated ? new HttpResponseMessage(HttpStatusCode.OK) : new HttpResponseMessage(HttpStatusCode.Unauthorized);
}
RouterModule.forRoot([
{
path: '',
canActivate: [AuthGuard] //provide the Injectable class here to authenticate.
component: MainComponent
},
{
path: 'contact',
component: ContentComponent
}
])