Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/434.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript angular 2显示/隐藏路由器出口并重定向到html页面_Javascript_Authentication_Angular_Typescript - Fatal编程技术网

Javascript angular 2显示/隐藏路由器出口并重定向到html页面

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 我可以隐藏菜

我创建了一个简单的应用程序。我有AD windows身份验证web api,它位于不同的域上,因此我启用了cors。我创建了一个api峰值,未经授权时返回401

app.service.ts

有两件事我很挣扎

  • 如何隐藏路由器出口(原因是我不想显示主页/链接)
  • 我可以使用主div上的[hidden]来隐藏它,但是如何重定向呢?因为
    将不可见
  • app.component.html

    authguard.ts

    auth.service.ts

    AuthenticateController.cs

    我可以隐藏菜单罚款,但homeComponent,这是搜索文本框呈现认证前,我想隐藏一切,只是想显示标志。这个工厂搜索文本框不应该显示,底部有gridview之类的数据,我在这张图片中没有显示


    在单击“取消”之前,它不会重定向…另一种解决方案就像我隐藏了homeComponent上的菜单一样,但有许多authService调用,这并不优雅,我猜在Angular 2 Routes中,您有“CanActivate”和“CanActivateChild”属性。 这可用于在呈现组件之前进行授权

    您可以在此处找到用法:

    在您的情况下,您不必卸下路由器出口

    相反:

  • 仅在app.component.html中添加
  • 提供2条路线

  • 需要授权的主要组件的默认路由
  • 与contact.html链接的联系人组件的单独路由(/contact)

    在应用程序模块中导入RouterModule以添加路由。
    例如:

  • 创建一个@Injectable类作为保护来验证用户。这将调用应用程序服务对用户进行身份验证,并在未经授权的情况下重定向到联系人组件。 您可以使用
    this.router.navigate(['contact'])从“@angular/Router”导入路由器

  • 添加这个新的@Injectable类作为默认路由的CanActivate属性

  • 谢谢,我今天将尝试这个,我不确定第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
    }
    ])