• 一般用法
  • Observable方式回傳

一般用法

其實網路上有好多教學文,

我簡單寫個紀錄.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
@Injectable()
export class GuardService implements CanActivate {
    constructor(
      private service: AppService,
      public loginService: loginService
    ) {}

  canActivate(): boolean {
    if (!this.loginService.isLogin()) {
      this.service.backLogin();
      return false;
    }
    return true;
  }
}
1
2
3
4
5
6
7
8
9
@Injectable()
export class AppService {

  constructor(private router: Router) {}

  backLogin(){
    this.router.navigate(['login']);
  }
}
  • 在RouteModule裡
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
const routes: Routes = [
  {
    path: "cms",
    component: CoreComponent,
    canActivate: [GuardService],
    children: CmsRouting
  },
  { path: "", redirectTo: "cms/home", pathMatch: "full" }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class CoreRoutingModule {}

Observable方式回傳

實務上通常都要等後端送使用者資訊回來,

才能確定裡面內容都可以看,

至於何時送回來呢

guard.service 以訂閱的方式來接

  • login service.ts
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
@Injectable()
export class LoginService {
  private loginSubject = new Subject<boolean>();

  loginState = this.loginSubject.asObservable();

  constructor() {}

  login() {
    this.loginSubject.next(true);
  }

  logout() {
    this.loginSubject.next(false);
  }
}
  • app.component.ts
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {
  constructor(private loginService: LoginService) {}
  ngOnInit() {
       this.dataService.ObWsModel(obj).subscribe(val => {
        if (!!val && !!val.Status && val.Status== 1) {
            this.loginService.login();
        } else {
            this.loginService.logout();
        }
    });
  }
}
  • app.service.ts
1
2
3
4
5
6
7
8
9
@Injectable()
export class AppService {

  constructor(private router: Router) {}

  backLogin(){
    this.router.navigate(['login']);
  }
}

以上述例子來說如果後端送回來的使用者狀態為1,

代表有權限登入,並觸發訂閱

  • guard.service.ts
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
@Injectable()
export class GuardService implements CanActivate {
    constructor(
      private service: AppService,
      private loginService: loginService
    ) {}

  canActivate(): Observable<boolean> {
    return this.loginService.loginState
      .map(e => {
        if (e) {
          return true;
        }
      })
      .catch(() => {
        this.service.backLogin();
        return Observable.of(false);
      });
  }
}