【发布时间】:2017-03-01 20:33:25
【问题描述】:
我有一个托管在 Heroku 中的 Angular 2 应用程序,我想将所有 http 请求重定向到 https,正确的方法是什么?谢谢!
【问题讨论】:
我有一个托管在 Heroku 中的 Angular 2 应用程序,我想将所有 http 请求重定向到 https,正确的方法是什么?谢谢!
【问题讨论】:
如果您希望将任何 URL 重定向到其 https 等效项,请将此类实现为服务。该类检查开发人员模式,以便仅当应用程序部署在 prod 中时才会发生重定向。
import {Injectable, isDevMode} from '@angular/core';
import {CanActivate, ActivatedRouteSnapshot} from '@angular/router';
@Injectable()
export class IsSecureGuard implements CanActivate {
canActivate(route: ActivatedRouteSnapshot): boolean {
if (!(isDevMode()) && (location.protocol !== 'https:')) {
location.href = 'https:' + window.location.href.substring(window.location.protocol.length);
return false;
}
return true;
}
}
这个守卫必须应用于每条路径。例如:
{path: 'mypath', component: MyPathComponent, canActivate: [IsSecureGuard]}
【讨论】: