我目前正在使用Angular 2构建一个Outlook加载项。
因为它是一个Outlook托管应用程序,它将在跨域iframe中运行,我无法改变这一点。 iframe也使用以下属性allow-scripts allow-forms allow-same-origin ms-allow-popups allow-popups
进行沙盒化。
我正在尝试使用Angular 2的路由器,但每当我使用navigate
方法时,我都会收到一系列例外情况,说明this._history.pushState is not a function
。我尝试了默认位置策略以及哈希位置策略,并在两者中获得此异常。我认为HashLocationStrategy
的目的是支持那些不完全支持HTML 5的旧版浏览器。似乎使用HTML 5 history
方法(例如pushState)来破坏目的,但我可能是我对LocationStrategy
和HashLocationStrategy
我的问题是,有没有办法告诉路由器不要使用history.pushState
或其他任何可以做的事情,以便我可以在这个iframe中使用路由器。因为我得到了这些异常,所以它会阻止我的一些应用程序启动代码执行。
答案 0 :(得分:2)
由于iFrame是Office.js,因此将window.history.replaceState()和window.history.pushState()设置为null。阻止破坏路由器的最简单方法是将它们设置为空函数,如下面的代码片段,然后就可以安全地使用HashLocationStrategy了。
<!DOCTYPE html>
<html>
<head>
<title>office add-in</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
...
<script>
window.history.replaceState = function(){};
window.history.pushState = function(){};
</script>
...
</head>
<body>
<addin></addin>
</body>
</html>
我在MSDN here上有一个代码示例,它有工作路由。
答案 1 :(得分:0)
您可以实施自己的LocationStrategy
。
您可以使用HashLocationStrategy
的来源作为模板。这不是很复杂https://github.com/angular/angular/blob/master/modules/angular2/src/router/location/hash_location_strategy.ts
要使Angular使用您的自定义LocationStrategy
,请在ROUTER_PROVIDERS
bootstrap(AppComponent, [
ROUTER_PROVIDERS,
provide(LocationStrategy, {useValue: CustomLocationStrategy})]);
答案 2 :(得分:0)
我遇到了同样的问题,试图让Angular 2路由工作。 RC1路由器和不推荐的路由器都有。 Gunter的建议是赢家,我已经在使用HashLocationStrategy了。我在GitHub上找到了这个类的最新源代码,基于它创建了我自己的自定义位置策略,并简单地删除了在路由发生时尝试更新Web浏览器历史记录的行。这样可以防止错误发生,并且此修复程序适用于已弃用的路由器及其更新的更新。
我写了一篇快速的博客文章,为那些感兴趣的人详细介绍了这些步骤: https://camerondwyer.wordpress.com/2016/06/17/getting-the-angular-2-router-working-for-an-office-addin/