Angular4.x의 라우팅 가드를 통해 동적 점프 인터페이스를 구현하는 단계에 대한 자세한 설명

php中世界最好的语言
풀어 주다: 2018-05-30 15:00:42
원래의
2422명이 탐색했습니다.

이번에는 Angular4에서 루트 가드를 통해 동적 점프 인터페이스를 구현하는 단계에 대해 자세히 설명하겠습니다.

요구사항: 현재 온라인몰 프로젝트를 진행하고 있으며, 사용된 기술은 Angular4.x입니다. 매우 일반적인 요구 사항이 있습니다. 사용자가 "내"

버튼

을 클릭하면 쿠키를 읽습니다. 데이터가 있으면 개인 정보 페이지로 이동하고, 그렇지 않으면 등록 또는 로그인 페이지로 이동합니다

해결책 여기서 이 기능은 Angular의 Route Guard를 통해 구현됩니다.

1. 라우팅 정보 구성

const routes = [
 { path: 'home', component: HomeComponent },
 { path: 'product', component: ProductComponent },
 { path: 'register', component: RegisterComponent },
 { path: 'my', component: MyComponent },
 { path: 'login', component: LoginComponent, canActivate: [RouteguardService] },//canActivate就是路由守卫
 { path: '', redirectTo: '/home', pathMatch: 'full' }
]
로그인 후 복사

2. Routeguard 조건(RouteguardService.ts)

import { Injectable, Inject } from "@angular/core";
import { DOCUMENT } from "@angular/common";
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router, NavigationStart } from "@angular/router";
import userModel from "./user.model";
@Injectable()
export class RouteguardService implements CanActivate {
  constructor(private router: Router, @Inject(DOCUMENT) private document: any) {
  }
  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    // this.setCookie("userId", "18734132326", 10);
    //读取cookie
    var cookies = this.document.cookie.split(";");
    var userInfo = { userId: "", pw: "" };
    if (cookies.length > 0) {
      for (var cookie of cookies) {
        if (cookie.indexOf("userId=") > -1) {
          userModel.accout = cookie.split("=")[0];
          userModel.password = cookie.split("=")[1];
          userModel.isLogin = false;
        }
      }
    }
    //获取当前路由配置信息
    var path = route.routeConfig.path;
    if (path == "login") {
      if (!userModel.isLogin) {
        //读取cookie如果没有用户信息,则跳转到当前登录页
        return true;
      } else {
        //如果已经登录了则跳转到个人信息页面,下面语句是通过ts进行路由导航的
        this.router.navigate(['product'])
      }
    }
  }
  setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
    var expires = "expires=" + d.toUTCString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
  }
}
로그인 후 복사
이 기사의 사례를 읽으신 후 방법을 숙지하셨을 것으로 믿습니다. PHP 중국어 웹사이트의 다른 관련 기사를 확인해보세요!

추천 자료:

React가 React-Router 라우팅에서 로그인 확인 제어를 구현하는 방법


Angular 라우팅에서 라우팅 가드를 사용하는 방법

위 내용은 Angular4.x의 라우팅 가드를 통해 동적 점프 인터페이스를 구현하는 단계에 대한 자세한 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!